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

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

我想提取directory_i_need。


当前回答

对于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

其他回答

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

这是我提取目录的部分:

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

谢谢你的帮助。

import os
## first file in current dir (with full path)
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
file
os.path.dirname(file) ## directory of file
os.path.dirname(os.path.dirname(file)) ## directory of directory of file
...

你可以继续这样做很多次,只要有必要……

编辑:从操作系统。路径,你可以使用os.path.split或os.path.basename:

dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file
## once you're at the directory level you want, with the desired directory as the final path node:
dirname1 = os.path.basename(dir) 
dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does.
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'

这应该也能达到目的。

对于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