Print Current Directory in Python

In this post, we will see how to print current directory in Python.

Files and Directories in Python

A computer system uses directories to store and organize files. Every file is present in some directory. There is a root folder at the top of the hierarchy, and every directory is a child of this root.

In Python, we have the current directory of a script file. We also have the current directory of the Python terminal. At times, both are the same especially when we work with Python notebook files.

Ways to print the Current Directory in Python

We will now discuss how to print the current directory in Python. We will deal with methods and display the directory of the running Python script or the current directory of the Python terminal.

Using the os.getcwd() function to print the current directory in Python

We have different functionalities in the os module that can communicate and interact with the operating system.

The current working directory is the directory in which the Python terminal is operating. At times, it may not be the directory of the Python script.

We can return the current working directory using the os.getcwd() function. It returns the directory as a string.

For example,

Output:

C:\Users\Username

Using the os.path module to print the current directory in Python

The os.path module provides different pathname-related functions. We can use them to print the current directory in Python.

The __file__ constant will be used in these methods and it represents the pathname of the Python script file. This path is relative to the current working directory. Remember, to use this constant we need to work in a .py file and not on a notebook file.

The os.path.realpath() function from this module can return the path of a given file. It removes any symbolic links present in the path. We can pass the __file__ constant to this function and we will get the path of the file we are working with. We can display this path to print the current directory in Python.

See the code below.

Output:

C:\Users\Username\file.py

In the above example, we can observe that this method prints the full path and the filename.

We can use the os.path.dirname() function to only print the current directory in Python without the filename. This function accepts a path with a filename and returns the directory.

For example,

Output:

C:\Users\Username

We can also split the result of the os.path.realpath() function. For this, we will use the os.path.split() function. It splits a given path into two parts. The second part contains the last component of the path and the first part contains everything up to the second part. We can use it to split the path and print the current directory in Python.

For example,

Output:

C:\Users\Username

Using the os.path.abspath() function to print the current directory in Python

This method may not work in all situations so should be used as a last resort. It returns the full pathname of the current file with the specified path. We can provide an empty string (think of it as an empty path), and it will return the path of the current file.

See the code below.

Output:

C:\Users\Username

Using the pathlib.Path.cwd() function to print the current directory in Python

Python 3.4 introduces a new efficient library to work with paths and filenames. The pathlib library was introduced to create and work with Path objects that can adapt to different operating systems.

The pathlib.Path class of this library has a variety of functions to work on path-related operations. We can use it to print the current directory in Python. The pathlib.Path.cwd() function can be used to return the current working directory in a pathlib object.

For example,

Output:

C:\Users\Username

Remember, this method returns the current working directory not the directory of the running file.

Using the pathlib.Path.resolve() function to print the current directory in Python

As discussed, we can work with pathnames with the pathlib.Path objects. We can specify the __file__ constant in the constructor of this class to create a pathlib object.

To get the full path with the filename, we can use the resolve() function. This method will return the full path and remove any symbolic links that occur in the path.

See the code below.

Output:

C:\Users\Username\file1.py

Using the pathlib.Path.parent attribute to print the current directory in Python

The pathlib.Path.parent library returns the parent of the given path. We can use it to remove the filename from the previous method and only print the current directory in Python.

See the code below.

Output:

C:\Users\Username

Using the locate.this_dir() function to print the current directory in Python

The locate module can also help to print the current directory in Python. We can use the this_dir() function from this library to return the directory of the current Python script.

For example,

Output:

C:\Users\Username

Conclusion

This tutorial demonstrated how to print the current directory in Python. To wrap up, we worked with three modules. These were the os, pathlib, and locate modules.

The getcwd() function of the os module returns the current working directory and its submodule os.path has different functions to return the current directory of the file. This module works with Python 2 as well.

We also discussed the pathlib library, which works with Python 3.4 and above. These methods were more efficient as they return pathlib objects with the current directory. The locate.this_dir() function also worked to print the current directory in Python.

THat’s all about how to print current directory in Python.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 21 December

    Save Object to File in Python

    Table of ContentsUse pickle.dump() FunctionUse dill.dump() FunctionUse pandas.to_pickle() Function Use pickle.dump() Function To save object to file in Python: Use the open() function with the with keyword to open the specified file. Use the pickle.dump() function to convert the object to a binary format to write it to the file. [crayon-63da5ac110997859655819/] [crayon-63da5ac11099e631057203/] Python’s pickle is […]

  • 18 December

    Write Binary File in Python

    Table of ContentsUse bytearray() FunctionUse bytes() FunctionUse struct.pack() FunctionUse encode() Function with join()Use to_bytes() Function Use bytearray() Function To write a binary file in Python: Use the bytearray() function to convert the list of bytes to a bytearray type object. Use a with clause with open() the method in write binary mode(wb) Use write() method […]

  • 26 November

    Remove Empty Lines from Text File in Python

    Table of ContentsUse isspace() MethodUse strip() MethodUse the FileInput() Method Use isspace() Method To remove empty lines from a Text File in Python: Open a file in read and write mode(r+). Use for loop for iterate over each line in the file. Use isspace() method to check if line is empty. if it is not […]

  • 16 November

    Create Temp File in Python

    Table of ContentsHow to Create Temp File in PythonUsing the tempfile.NamedTemporaryFile objectUsing the tempfile.TemporaryFile objectUsing the mkstemp() functionConclusion Sometimes applications require storage and processing of temporary data. For such purposes, Python provides the tempfile library that can be used to create such files and directories. How to Create Temp File in Python This tutorial will […]

  • 02 October

    Get Temp Directory in Python

    Table of ContentsGet Temp Directory in PythonUsing the tempfile.Gettempdir() Function to Get Temp Directory in PythonUsing the tempfile.Gettempdirb() Function to Get Temp Directory in PythonUsing the tempfile.Tempdir Variable to Get Temp Directory in PythonConclusion Sometimes we can encounter scenarios where we wish to store temporary data in Python. This can include situations of creating temporary […]

  • 19 May

    Remove Extension From Filename in Python

    Table of ContentsHow to Remove Extension From Filename in Python?Remove Extension From Filename in Python Using the os ModuleRemove Extension From Filename in Python using the pathlib moduleRemove Multiple File Extensions Using pathlib Module in PythonConclusion While programming in python, we often have to deal with file names. In this article, we will discuss how […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.