For example, a method is passed a path as a parameter, this path might be "C:/a/b/c/d", what if I want to use os.chdir() to change to C:/a/b/c (without the last folder)? Can os.chdir() take the ".." command?
Asked
Active
Viewed 9,877 times
2
-
"Try it out" is not the most reliable approach if you want to be flexible across platforms. – Jeremy Jun 10 '11 at 12:27
-
2Although depending on symlinks, going to d and then up a level may not work out the same as going to c. – Thomas K Jun 10 '11 at 12:27
-
hair, note that “..” is not a command; in all POSIX-conformant operating systems and their filesystems (yes, that includes MS Windows) and then some, all directories have a valid entry named “..” (although there is special code to cater for the fact that a `chdir` from `/a/b/c` to `..` results in `/a/b` as the *current working directory*, not `/a/b/c/..`, even if the latter is valid). – tzot Jun 10 '11 at 16:28
3 Answers
10
os.chdir()
can take '..'
as argument, yes. However, Python provides a platform-agnostic way: by using os.pardir
:
os.chdir(os.pardir)

Thomas Wouters
- 130,178
- 23
- 148
- 122
3
You could use os.path.dirname
:
In [1]: import os.path
In [2]: os.path.dirname('C:/a/b/c/d')
Out[2]: 'C:/a/b/c'
edit: It's been pointed out that this doesn't remove the last component if the path ends with a slash. As a more robust alternative, I propose the following:
In [5]: os.path.normpath(os.path.join('C:/a/b/c/d', '..'))
Out[5]: 'C:/a/b/c'
In [6]: os.path.normpath(os.path.join('C:/a/b/c/d/', '..'))
Out[6]: 'C:/a/b/c'
The '..'
can be replaced with os.path.pardir
to make the code even more portable (at least theoretically).

NPE
- 486,780
- 108
- 951
- 1,012
-
as Sven pointed out when I answered this: This method fails if there is a trailing slash. `os.path.dirname("/a/b/c/") == "/a/b/c"`. – Jeremy Jun 10 '11 at 12:33
2
The os.path module has some functions that are useful for this sort of thing.
os.path.normpath()
can be used to convert a path containing references like ..
to an absolute path. This would ensure consistent behaviour regardless of how the operating system handles paths.
os.chdir(os.path.normpath("C:/a/b/c/.."))
should accomplish what you want.

Jeremy
- 1
- 85
- 340
- 366
-
-
-
os.path.normpath(os.getcwd() + os.sep + os.pardir) Will get you back one – chimpsarehungry Jul 18 '13 at 14:42