且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取文件的父目录?

更新时间:2023-02-21 14:41:51

使用 os.path.dirname 获取目录路径.如果你只想要目录的名字,你可以使用 os.path.basename 从中提取基本名称:

>>>路径 = r'c:\xxx\abc\xyz\fileName.jpg'>>>导入操作系统>>>os.path.dirname(路径)'c:\\xxx\\abc\\xyz'>>>os.path.basename(os.path.dirname(path))'xyz'

Given a path to a file, c:\xxx\abc\xyz\fileName.jpg, how can I get the file's parent folder? In this example, I'm looking for xyz. The number of directories to get to the file may vary.

Use os.path.dirname to get the directory path. If you only want the name of the directory, you can use os.path.basename to extract the base name from it:

>>> path = r'c:\xxx\abc\xyz\fileName.jpg'
>>> import os
>>> os.path.dirname(path)
'c:\\xxx\\abc\\xyz'
>>> os.path.basename(os.path.dirname(path))
'xyz'