我需要提取某个路径的父目录的名称。这就是它的样子:
c:\stuff\directory_i_need\subdir\file
我正在使用其中使用directory_i_need
名称(而不是路径)的内容修改“文件”的内容。我创建了一个函数,它将为我提供所有文件的列表,然后......
for path in file_list:
#directory_name = os.path.dirname(path) # this is not what I need, that's why it is commented
directories, files = path.split('\\')
line_replace_add_directory = line_replace + directories
# this is what I want to add in the text, with the directory name at the end
# of the line.
我该怎么做?
答案 0 :(得分:174)
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的编辑,您可以使用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.
答案 1 :(得分:25)
在Python 3.4中,您可以使用pathlib module:
>>> from pathlib import Path
>>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe')
>>> p.name
'iexplore.exe'
>>> p.suffix
'.exe'
>>> p.root
'\\'
>>> p.parts
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
>>> p.relative_to('C:\Program Files')
WindowsPath('Internet Explorer/iexplore.exe')
>>> p.exists()
True
答案 2 :(得分:4)
首先,看看splitunc()
中是否有os.path
作为可用功能。返回的第一个项目应该是您想要的...但我在Linux上,当我导入os
并尝试使用它时,我没有此功能。
否则,完成工作的一种半丑陋的方式是使用:
>>> 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'
显示检索文件正上方的目录,以及正好在该文件上方的目录。
答案 3 :(得分:1)
这就是我提取目录的一部分:
for path in file_list:
directories = path.rsplit('\\')
directories.reverse()
line_replace_add_directory = line_replace+directories[2]
感谢您的帮助。
答案 4 :(得分:0)
如果您使用pathlib
,则只需parent
部分。
from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent)
将输出:
C:\Program Files\Internet Explorer
如果您需要所有部分(已经包含在其他答案中),请使用parts
:
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts)
然后您将获得一个列表:
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
节省时间。
答案 5 :(得分:0)
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'
这也可以解决问题。
答案 6 :(得分:-1)
您必须将整个路径作为参数放入os.path.split。见The docs。它不像字符串拆分那样工作。