Moving up one directory in Python
Question:
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
Answers:
Using os.chdir
should work:
import os
os.chdir('..')
>>> import os
>>> print os.path.abspath(os.curdir)
C:Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:
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'
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.
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.
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.
Combine Kim’s answer with os:
p=Path(os.getcwd())
os.chdir(p.parent)
A convenient way to move up multiple directories is pathlib
:
from pathlib import Path
full_path = "C:Program FilesPython37libpathlib.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 FilesPython37lib
C:Program FilesPython37
C:Program Files
C:
['C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Program Files', 'C:\']
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
Using os.chdir
should work:
import os
os.chdir('..')
>>> import os
>>> print os.path.abspath(os.curdir)
C:Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:
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'
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.
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.
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.
Combine Kim’s answer with os:
p=Path(os.getcwd())
os.chdir(p.parent)
A convenient way to move up multiple directories is pathlib
:
from pathlib import Path
full_path = "C:Program FilesPython37libpathlib.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 FilesPython37lib
C:Program FilesPython37
C:Program Files
C:
['C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Program Files', 'C:\']