I've found it useful to have a contextmanager
version of os.chdir()
: on exit it chdir()
s back to the original directory.
This allows you to emulate a common (Bourne) shell-scripting pattern:
(
cd <some dir>
<do stuff>
)
I.e. you change to a new dir <some dir>
inside a subshell (the (
)
) so that you are sure to return to your original dir, even if the <do stuff>
causes an error.
Compare the context manager and vanilla versions in Python. Vanilla:
original_dir = os.getcwd()
os.chdir(<some dir>)
try:
<do stuff>
finally:
os.chdir(original_dir)
Using a context manager:
with os.chdir(<some dir>):
<do stuff>
The latter is much nicer!