How do I get the parent directory in Python?
from pathlib import Pathpath = Path("/here/your/path/file.txt")print(path.parent.absolute())
import osprint os.path.abspath(os.path.join(yourpath, os.pardir))
yourpath is the path you want the parent for.
os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender's answer using
The Pathlib method (Python 3.4+)
from pathlib import PathPath('C:\Program Files').parent# Returns a Pathlib object
The traditional method
import os.pathos.path.dirname('C:\Program Files')# Returns a string
Which method should I use?
Use the traditional method if:
You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)
Your Python version is less than 3.4.
You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.
If none of the above apply, use Pathlib.
What is Pathlib?
If you don't know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I've highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.
Navigating inside a directory tree:
'/etc') q = p / 'init.d' / 'reboot'qPosixPath('/etc/init.d/reboot') q.resolve()PosixPath('/etc/rc.d/init.d/halt')p = Path(
Querying path properties: