Moving up one directory in Python

PythonDirectory

Python Problem Overview


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

Python Solutions


Solution 1 - Python

>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\

Solution 2 - Python

Using os.chdir should work:

import os
os.chdir('..')

Solution 3 - Python

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'

Solution 4 - Python

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.

Solution 5 - Python

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.

Solution 6 - Python

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.

Solution 7 - Python

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:\\']

Solution 8 - Python

Combine Kim's answer with os:

p=Path(os.getcwd())
os.chdir(p.parent)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2165857View Question on Stackoverflow
Solution 1 - PythonRyan GView Answer on Stackoverflow
Solution 2 - PythonSteve AllisonView Answer on Stackoverflow
Solution 3 - PythonConan LiView Answer on Stackoverflow
Solution 4 - PythonKimView Answer on Stackoverflow
Solution 5 - PythonaychedeeView Answer on Stackoverflow
Solution 6 - PythonRadek DView Answer on Stackoverflow
Solution 7 - PythonMilovan TomaševićView Answer on Stackoverflow
Solution 8 - PythonmLstudent33View Answer on Stackoverflow