The Python Equivalent of Shell ‘cd’ Command

featured_image

While working with Shell, most of us use ‘cd’ to change working directories easily. But can there be a way to switch directories in Python? Let’s find the answer to this simple question and see how Python eases our lives differently!

Also Read: Python Equivalent to Java Final Keyword

Python’s OS Library for Directory Navigation

As Python helps individuals work with hardware and software, its beauty lies within its libraries. One such library is the ‘OS’ module which allows us to interact with our computer’s operating system. Inside the ‘OS’ module, we have the function named ‘os.chdir()’, which can serve the same purpose as the shell ‘cd’ command. Here we take an example.

import os

current_dir = os.getcwd()
print(f"Current Working Directory: {current_dir}")

new_dir =  r"C:\Users\Lenovo\Documents\Py"
os.chdir(new_dr)

updated_dir = os.getcwd()
print(f"Updated Working Directory: {updated_dir}")

Run this script in any code editor. Here I have used Visual Studio for reference.

Os_Example
Os_Example

At first, we have imported the ‘os’ module using the import statement. Second, we have created two variables; ‘current_dir’ which holds the path of the current directory in action, and ‘new_dir’ is the path of a directory that we want to move to. Thus keeping this in track, we use the ‘os.chdir()’ function and pass the new file path as argument. Once the file changes, we print the new directory to verify the change.

Thus, ‘os.chdir()’ is the equivalent of the Shell ‘cd’ command.

Also Read: Python Equivalent to Java Final Keyword

Advantages of Using Python

As we know, Python has powerful libraries that implement complex topics easily, we can also use other features to enhance our performance. Let’s look at a few methods to switch directories efficiently.

  • Use Exception Handling

You must have observed that while moving from one directory to another in Shell, the ‘cd’ command leads to unexpected system crashes. To prevent such errors, Python comes with in-built tools like try-catch blocks. These blocks define cases where a crash may occur and let us handle them by showing the error message in time. Thus one can easily track the crashes and the reasons behind them.

import os

def change_directory(directory):
    try:
        os.chdir(directory)
        print(f"Changed to directory: {directory}")
    except FileNotFoundError:
        print(f"Directory not found: {directory}")
    except PermissionError:
        print(f"Permission denied for directory: {directory}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

change_directory("/nonexistent/directory")
exception_handling
exception_handling

First I have added a try block inside the function change_directory that will check the action of changing the directory by os.chdir() method. If the method os.chdir() cannot find the directory, it will print the error message. Likewise, if a file or folder needs system permission or any unexpected system crash occurs, it will print the error message. Here I have provided a fake directory link “/nonexistent/directory” in the function and it prints the message as shown. This way we can keep track of unexpected crashes and make corrections as required.

  • Use Context Managers

Often while working with directories in Python, we are required to move back and forth between files. You can manage this task efficiently by using ‘pathlib’ library in Python. This library has a method ‘contextlib’ which temporarily takes up a new directory, performs the required operation and returns to the original directory.

import os
from contextlib import contextmanager

@contextmanager
def temporary_directory(new_directory):
    current_directory = os.getcwd()
    try:
        os.chdir(new_directory)
        print(f"Changed to directory: {new_directory}")
        yield
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        os.chdir(current_directory)
        print(f"Returned to original directory: {current_directory}")

with temporary_directory(r"C:\Users\Lenovo\Documents\Py"):
    print(f"Current working directory inside block: {os.getcwd()}")

print(f"Current working directory outside block: {os.getcwd()}")
context_manager
context_manager

First, we have called the ‘os’ and ‘contextmanger’ using the import statement. Inside the function temporary_directory, we first store the current directory path in a variable and using the os.chdir() method switch to the new directory. After moving to a new directory in the try block, the yield keyword will make Python skip to the with block. The ‘with’ blocks operate with the new directory and perform operations like here I have printed a simple statement. After completing the ‘with’ block, it returns to function and prints the statement in ‘finally’ block. Here if any system crash occurs, Python will print the exception in place of going to the ‘with’ block. Lastly, Python comes back to the original directory and prints the statement as shown.

What is the equivalent of Shell ‘cd’ in Python?

As Python comes with powerful libraries, the ‘os’ library is one such module that helps to shift between directories. Inside the ‘os’ module, ‘chdir()’ method can be used like ‘cd’ to change directories in Python. Thus ‘os.chdir()’ is equivalent to the Shell ‘cd’ command.

What advantages does Python offer in working with system files?

In Python, one can use tools like try-catch blocks for handling exceptions and understanding the reason behind unexpected system crashes. Likewise, we can use context managers to temporarily switch to the new directory, perform the operation inside the directory and return to the original directory.

The Conclusion

To sum up, we can use Python to switch between different directories within the program itself. It offers a library named the ‘os’ module that has a method ‘chdir()’ used to change directories like the ‘cd’ command in the Shell. Further Python also allows us to use tools like try-catch blocks for handling exceptions and understanding the reasons behind them in time. Another tool that we can use is a context manager which temporarily changes the directory, performs the required operation and returns to the original directory.

References

python – Equivalent of shell ‘cd’ command to change the working directory? – Stack Overflow

https://docs.python.org/3/library/contextlib.html