簡體   English   中英

在 Python 中提取文件路徑(目錄)的一部分

[英]Extract a part of the filepath (a directory) in Python

我需要提取某個路徑的父目錄的名稱。 這是它的樣子:

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

我想提取directory_i_need

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.

對於 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

如果您使用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')

節省時間。

首先,查看您是否將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'

它顯示檢索文件正上方的目錄,以及正上方的目錄。

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'

這也應該可以解決問題。

這是我為提取目錄所做的工作:

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

感謝您的幫助。

您必須將整個路徑作為 os.path.split 的參數。 請參閱文檔 它不像字符串拆分那樣工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM