在Python中提取文件路径(目录)的一部分

2024-05-16 21:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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.

我该怎么做?


Tags: 文件thepathnamein路径名称is
3条回答

在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
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.

首先,看看是否有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'

它显示了检索文件上方的目录,以及文件上方的目录。

相关问题 更多 >