我需要提取某个路径的父目录的名称。这是它的样子:

C:\stuff\directory_i_need\subdir\file.jpg

我想提取directory_i_need。


当前回答

首先,查看在os.path中是否有splitunc()作为可用函数。返回的第一项应该是你想要的…但是我在Linux上,当我导入操作系统并尝试使用它时,我没有这个功能。

否则,一种半丑陋的完成工作的方法是使用:

>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'

其中显示检索文件上面的目录,以及文件上面的目录。

其他回答

import os

directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

这应该也能达到目的。

首先,查看在os.path中是否有splitunc()作为可用函数。返回的第一项应该是你想要的…但是我在Linux上,当我导入操作系统并尝试使用它时,我没有这个功能。

否则,一种半丑陋的完成工作的方法是使用:

>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'

其中显示检索文件上面的目录,以及文件上面的目录。

你必须把整个路径作为os。path。split的参数。请看医生。它不像字符串分割那样工作。

这是我提取目录的部分:

for path in file_list:
  directories = path.rsplit('\\')
  directories.reverse()
  line_replace_add_directory = line_replace+directories[2]

谢谢你的帮助。

对于Python 3.4+,请尝试pathlib模块:

>>> from pathlib import Path

>>> p = Path('C:\\Program Files\\Internet Explorer\\iexplore.exe')

>>> str(p.parent)
'C:\\Program Files\\Internet Explorer'

>>> p.name
'iexplore.exe'

>>> p.suffix
'.exe'

>>> p.parts
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')

>>> p.relative_to('C:\\Program Files')
WindowsPath('Internet Explorer/iexplore.exe')

>>> p.exists()
True