68

Is there a simple way to move up one directory in python using a single line of code? Something similar to cd .. in command line

user2165857
  • 2,530
  • 7
  • 27
  • 39

9 Answers9

113
>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\
Ryan G
  • 9,184
  • 4
  • 27
  • 27
52

Using os.chdir should work:

import os
os.chdir('..')
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Steve Allison
  • 1,091
  • 6
  • 6
17

Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath

so that you could do something like this:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'
Conan Li
  • 474
  • 2
  • 6
  • 1
    In python3.4 the *pathlib* was introduced, which was meant to tackle the same problem (refer to my answer for more details). – Kim Jan 14 '17 at 16:56
15

Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:

import os
os.chdir(os.path.dirname(os.getcwd()))

That gets the current working directory, steps up one directory, and then changes to that directory.

aychedee
  • 24,871
  • 8
  • 79
  • 83
  • 9
    also, with slightly less typing, `os.chdir(os.path.pardir)`. This answer is slightly more platform independent, but it is sort of a moot point because while you could imagine a platform that doesn't represent `..` as the parent directory, any platform that anyone currently uses (including both windows and UNIX) do represent it that way. – aestrivex Jul 26 '13 at 16:15
  • Yeah you're right! I just finished testing it on a windows box, and `..` works fine. I always expect so little of windows but it does sometimes surprise me :). Still, magic strings littering my code always bother me. – aychedee Jul 26 '13 at 16:19
  • I agree, but just musing: I wonder if there will *ever* be a real system that doesn't use this particular convention. – aestrivex Jul 26 '13 at 20:07
  • I hope not. Unix 4 life. – aychedee Jul 27 '13 at 07:54
  • 1
    how come this move one directory up? I don't understand by the code. What if I want to move two directories up? – alansiqueira27 Sep 20 '18 at 15:18
  • You could try running each part of the code in a Python shell? It would demonstrate what is happening here. If you wanted to move two directories up, you would have to insert another call to `os.path.dirname`. – aychedee Sep 28 '18 at 14:21
  • For the answer from @aestrivex, this works great. This also works if the [`.path` part is excluded](https://docs.python.org/3/library/os.html#os.pardir): `os.chdir(os.pardir); print(os.getcwd())` – edesz Jun 09 '19 at 17:19
14

In Python 3.4 pathlib was introduced:

>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')

It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.

For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.

Kim
  • 1,361
  • 3
  • 18
  • 24
2

Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd() method doesn't work as expected. This is what I would do:

import os

# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))

print(curDir) # print current directory

Define a function like this:

def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
    for _ in range(n):
        path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that 
                                                        # the function iterates proper number of times
    return(path)

The use of this function is fairly simple - all you need is your path and number of directories up.

print(dir_up(curDir,3)) # print 3 directories above the current one

The only minus is that it doesn't stop on drive letter, it just will show you empty string.

Radek D
  • 79
  • 10
1

A convenient way to move up multiple directories is pathlib:

from pathlib import Path
    
full_path = "C:\Program Files\Python37\lib\pathlib.py"
print(Path(full_path).parents[0])
print(Path(full_path).parents[1])
print(Path(full_path).parents[2])
print(Path(full_path).parents[3])

print([str(Path(full_path).parents[i]) for i in range(4)])

output:

C:\Program Files\Python37\lib
C:\Program Files\Python37
C:\Program Files
C:\

['C:\\Program Files\\Python37\\lib', 'C:\\Program Files\\Python37', 'C:\\Program Files', 'C:\\']
Milovan Tomašević
  • 6,823
  • 1
  • 50
  • 42
0

Combine Kim's answer with os:

p=Path(os.getcwd())
os.chdir(p.parent)
mLstudent33
  • 1,033
  • 3
  • 14
  • 32
0

If you assigned path to variable and want to go up one directory.

p = os.getcwd()
up_dir = os.path.join(p, "..")
abs_path = os.path.abspath(up_dir)
bhargav3vedi
  • 521
  • 1
  • 6
  • 11