How can I go back to the previous working directory after changing it?

Question:

In Python, how can I get the effect of cd - in the shell? That is, after changing the working directory, how can I set it back to what it was before that change?

Asked By: kplus

||

Answers:

You’re looking to change the working directory? The OS module in python has a lot of functions to help with this.

import os
os.chdir( path )

path being ".." to go up one directory. If you need to check where you are before/after a change of directory you can issue the getcwd() command:

mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd)     # go back where you came from
Answered By: Mike
path = os.path.dirname(__file__)
print(path)

will print the CWD of the file, say C:UsersTestDocumentsCodeRevampJoke

path2 = os.path.dirname(path)
print(path2)

will print the Parent directory of of the file: C:UsersTestDocumentsCodeRevamp

Answered By: Chinmay Hegde

This is not directly supported. Instead, check what the current working directory is before the change, and save it in a variable; then it will be possible to change to that directory later.

To streamline the process, consider using a context manager to reset the path automatically after a temporary change. For example:

import os
from contextlib import contextmanager

@contextmanager
def temp_chdir(where):
    old = os.getcwd()
    try:
        os.chdir(where)
        yield
    finally:
        os.chdir(old)

which allows code like

with temp_chdir('/some/other/path') as f:
    print(os.listdir('.'))

The CWD will be restored after the with block, even if an exception is raised.

Answered By: Karl Knechtel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.