How to Get and Change the Current Working Directory in Python

Introduction

Before we begin talking about how to get and change the current working directory in python, let's briefly understand - What is Python?

Python is a high-level, interpreted, and general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python emphasizes readability, simplicity, and ease of use, making it a popular choice for beginners and experienced developers alike.

It is always a good idea to use absolute paths when working with files in directories in Python. An absolute path begins at the root directory and ends at the current working directory, whereas a relative path begins at the current working directory and ends at the root directory.

The os python module allows you to communicate with the operating system on the go. The module is part of the Python standard library and contains methods for locating and modifying the current working directory.

In this tutorial, you will get and change the current working directory in Python. We will also address a few FAQs on how to get and change the current working directory in Python.

Getting the Current Working Directory in Python

The os module's getcwd() method returns a string with the absolute path to the current working directory. The trailing slash character is not included in the output string.

os.getcwd()

You must import the os module at the top of the program to use its methods.

An example of how to print the current working directory is given below:

# Import the os module
import os

# Get the current working directory
cwd = os.getcwd()

# Print the current working directory
print("Current working directory: {0}".format(cwd))

# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

You will get an output like below:

Output

Current working directory: /home/linuxize/Desktop
os.getcwd() returns an object of type: <class 'str'>
💡
Use os.path.realpath( file ) to find the directory where the script is located. It'll provide you a string with the absolute path of the currently running script.

Changing the Current Working Directory in Python

The chdir() function in Python is used to change the current working directory.

os.chdir(path)

The procedure only takes one argument, which is the path to the directory you want to change to. It's possible to specify an absolute or relative path in the path argument.

Below is an example:

# Import the os module
import os

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Change the current working directory
os.chdir('/tmp')

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

You will get an output like below:

Output

Current working directory: /home/linuxize/Desktop
Current working directory: /tmp

The chdir() method's parameter must be a directory; otherwise, the NotADirectoryError exception is thrown. A FileNotFoundError exception is thrown if the supplied directory does not exist. A PermissionError exception is thrown if the user running the script does not have the required permissions.

# Import the os module
import os

path = '/var/www'

try:
    os.chdir(path)
    print("Current working directory: {0}".format(os.getcwd()))
except FileNotFoundError:
    print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
    print("{0} is not a directory".format(path))
except PermissionError:
    print("You do not have permissions to change to {0}".format(path))

FAQs on How to Get and Change the Current Working Directory in Python

How can I change the current working directory in Python? 

To change the current working directory, you can use the os module's chdir() function. Pass the path of the desired directory as a string to this function. Example: import os; os.chdir('/path/to/new/directory')

Can I use a relative path instead of an absolute path when changing the directory? 

Yes, you can use both relative and absolute paths when changing the directory using chdir(). Relative paths are resolved based on the current working directory.

How can I handle errors when changing the current working directory in Python? 

The chdir() function may raise an exception if there is an error during the directory change. To handle such exceptions, you can use the try-except block to catch and handle any potential errors that may occur.

How can I list the contents of the current working directory in Python? 

You can use the os module's listdir() function to list the contents of the current working directory. It returns a list of filenames and directories present in the current directory.

How can I check if a path is a file or a directory using Python? 

You can use the os.path module's functions like isfile() and isdir() to check if a given path points to a file or a directory, respectively. These functions return a Boolean value indicating whether the path is a file or directory.

How do I create a new directory in Python?

You can create a new directory using the os module's mkdir() function. Provide the desired directory name as a string and use the function to create it in the current working directory.

How can I get the username of the current user in Python?

The username of the current user can be obtained using the getpass module's getuser() function. It returns the username associated with the current user running the Python script.

Conclusion

Understanding how to get and change the current working directory in Python is essential for navigating the file system, performing file operations, and executing scripts in the desired context.

Python provides the os and os.path modules, among others, that offer functions and methods to accomplish these tasks. By utilizing these tools, you can retrieve the current working directory, list its contents, change directories, create new directories, check if a path is a file or directory, and perform other file-related operations.

Additionally, understanding concepts like relative and absolute paths, handling errors, and obtaining information such as file sizes and usernames further enhances your capabilities.


If you have any queries, please leave a comment below, and we’ll be happy to respond to them for sure.