cd
is the shell command to change the working directory.
How do I change the current working directory in Python?
os.chdir()
is the Pythonic version of cd
.
cd()
is easy to write using a generator and a decorator.
from contextlib import contextmanager
import os
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
Then, the directory is reverted even after an exception is thrown:
os.chdir('/home')
with cd('/tmp'):
# ...
raise Exception("There's no place like home.")
# Directory is now back to '/home'.