Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Change To A Different Directory In Python

Use ` os.chdir(PATH) [TODO: Code shorthand span ] to change directories in a python script. For example :

python
import os

os.chdir("/some/path")

That line will attempt to change into the specified path and throw an error if it can't.

Dealing With Errors

This approach catches the errors that can show up when attempting to change directories

python
import os

try:
    os.chdir("/Users/alan/Desktop")
    print("In new directory")

except FileNotFoundError:
    print("Directory does not exist")

except NotADirectoryError:
    print("Not a directory")

except PermissionError:
    print("Not allowed in directory")