Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Change To A Different Directory In Python

Use `os.chdir(PATH)`python` to change directories in a python script. For example:

Code

import os

os.chdir("/some/path")

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

Code

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")