13

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
kplus
  • 307
  • 1
  • 4
  • 16
  • Busy, can't give a full response. But what you're looking for is [`subprocess`](http://docs.python.org/2/library/subprocess.html) and `subprocess.popen`. Pass `'cd -'` to the subprocess – inspectorG4dget Jan 22 '13 at 16:07
  • This question has been answered elsewhere on this site: http://stackoverflow.com/questions/431684/how-do-i-cd-in-python – Arthur Richards Jan 22 '13 at 16:08
  • 1
    No I understand the `chdir`, but can you change it relative to the directory you are currently in? (Move back a directory without specifying full path) – kplus Jan 22 '13 at 16:09

3 Answers3

18

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
Mike
  • 47,263
  • 29
  • 113
  • 177
  • Quick question, how would I go into a directory that is in the current directory without specifying the full path? @Mike – kplus Jan 22 '13 at 20:46
  • @SensulPanda - go into the current directory? By definition you're already in the current directory. :) but the "short cut" to cwd is "." `os.chdir(".")`, but again, since you're already in the current directory I'm not sure that would help. – Mike Jan 22 '13 at 20:57
  • Not exactly what I meant. I mean let's say im in a directory called `/example/`. There is a folder in that directory called `test`. If i wanted to write a file to that directory, you would assume the code would look like `/example/test` for a relative directory, but it forces you to specify the full path. – kplus Jan 22 '13 at 21:00
  • 1
    @SensulPanda - gottcha, yeah, pretty much what I just suggested, the relative path is: `"./test"` that is equivalent to `//example/test` if your current working directory is "example" – Mike Jan 22 '13 at 21:10
  • 2
    Use ``scriptdir = os.path.dirname(os.path.abspath(__file__))`` if you want to make paths relative to the script, else otherwise it'll be relative to your ``pwd`` which is sometimes what you want. – sotapme Feb 07 '13 at 19:03
  • This answer doesn't answer the question. The author asks for an equivalent of linux's `cd -` (change directory to the previous one, not the parent one). – Alexandru Irimiea May 07 '16 at 21:44
  • 1
    @AlexandruIrimiea - How do you figure this doesn't answer the question? The example I gave is *exactly* the same as `cd -`. I chose to use the parent directory `".."` as the example, but you could put any other directory in there and the example works just the same, just as `cd -` does. As a side note to that.. the check mark general means the author has noted that particular answer as the answer to the question that solves the problem. – Mike May 15 '16 at 06:33
0
path = os.path.dirname(__file__)
print(path)

will print the CWD of the file, say C:\Users\Test\Documents\CodeRevamp\Joke

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

will print the Parent directory of of the file: C:\Users\Test\Documents\CodeRevamp

Chinmay Hegde
  • 61
  • 1
  • 4
0

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153