How do I change directory back to my original working directory with Python?

A context manager is a very appropriate tool for this job:

from contextlib import contextmanager
import os

def cwd(path):
    oldpwd = os.getcwd()

…used as:

os.chdir('/tmp') # for testing purposes, be in a known directory
print(f'before context manager: {os.getcwd()}')
with cwd(""):
    # code inside this block, and only inside this block, is in the new directory
    print(f'inside context manager: {os.getcwd()}')

print(f'after context manager: {os.getcwd()}')

…which will yield something like:

before context manager: /tmp
inside context manager: /
after context manager: /tmp

This is actually superior to the cd - shell builtin, inasmuch as it also takes care of changing directories back when a block is exited due to an exception being thrown.

For your specific use case, this would instead be:

with cwd(testDir):

Another option to consider is using instead of os.system(), which will let you specify a working directory for the command to run:

# note: better to modify this to not need shell=True if possible, cwd=testDir, shell=True)

… which would prevent you from needing to change the interpreter’s directory at all.

Note that now it is recommended to use (instead of call) but the same arguments are available, and in particular cwd:

Leave a Comment