如何在 Python 中從檔案路徑獲取檔名?


在本文中,我們將學習一個 Python 程式,用於從檔案路徑獲取檔名。

使用的方法

以下是完成此任務的各種方法:

  • 使用 OS 模組函式

  • 使用 Pathlib 模組

  • 使用正則表示式(regex 模組)

方法 1:使用 OS 模組函式

使用 split() 函式從檔案路徑獲取檔名

split() 函式將字串拆分為列表。我們可以定義分隔符;預設分隔符是任何空格。

演算法(步驟)

以下是執行所需任務應遵循的演算法/步驟:

  • 使用 import 關鍵字匯入 os 模組。

  • 建立一個變數來儲存輸入檔案路徑。

  • 使用split() 函式根據 '/' 分隔符將檔案路徑拆分為單詞列表。

  • 使用負索引(從末尾開始索引,即 -1、-2 等)從列表中獲取最後一個元素。

  • 列印結果檔名。

示例

以下程式使用 split() 函式從給定的檔案路徑返回檔名:

# importing os module 
import os
 
# input file path 
inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf'

# Printing the given file path
print("The given file path is:",inputFilepath)
# splitting the file path into a list of words based on '/' and 
# getting the last element using negative indexing 
print("The File Name is:\n",os.path.basename(inputFilepath).split('/')[-1])

輸出

執行後,以上程式將生成以下輸出:

The given file path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf
The File Name is:
 tutorialsPoint.pdf

使用 os.path.basename 從檔案路徑獲取檔名

使用內建 Python 函式os.path.basename(),可以確定指定路徑中的基本名稱。函式path.basename()返回路徑名 path 的基本名稱,它接受一個 path 引數。

示例

以下程式使用 os.path.basename() 函式從給定的檔案路徑返回檔名:

# importing os module
import os
 
# input path of the file 
inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf'
 
# Printing the given input path
print("Give Input Path is:",inputFilepath)
 
# getting the last component(main file name )of the input file path
print("The File Name is:\n",os.path.basename(inputFilepath))

輸出

執行後,以上程式將生成以下輸出:

Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf
The File Name is:
 tutorialsPoint.pdf

使用 os.splitext() 從檔案路徑獲取檔名

如果我們只需要沒有副檔名的檔名或僅副檔名,此方法將生成檔案及其副檔名。這裡,os 模組的 splitext 函式發揮作用。

os.splitext() 方法將返回一個字串元組,其中包含檔名和內容,我們可以使用索引訪問它們。

示例

以下程式使用 os.splitext() 函式從給定的檔案路徑返回檔名:

# importing os module 
import os

inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf'
# Printing the given input path
print("Give Input Path is:",inputFilepath)

# getting the file name from the file path
fileName = os.path.basename(inputFilepath)
# splitting the file using the splittext() function 
full_file = os.path.splitext(fileName)
# printing the tuple of a string containing file name and extension separately
print(full_file) 
# Concatenating file name with file extension using string concatenation
print("The File Name is:\n",full_file[0] + full_file[1])

輸出

Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf
('tutorialsPoint', '.pdf')
The File Name is:
 tutorialsPoint.pdf

方法 2:使用 Pathlib 模組

Python Pathlib 模組中提供了多個類,這些類描述了具有適合多種作業系統的語義的檔案系統路徑。此模組是 Python 基本實用程式模組之一。

如果我們想要帶有副檔名的檔案,我們可以使用 name 屬性,即使stem是允許從連結中提取不帶副檔名的檔名的實用程式屬性之一。

示例

以下程式使用Path() 函式和 Pathlib 模組的 stem 屬性從給定的檔案路徑返回檔名:

# importing Path from pathlib module
from pathlib import Path
 
# input file path 
inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf'
 
# getting the filename from the file path 
# here the stem attribute extracts the file name from filepath
print('File Name is:',Path(inputFilepath).stem)
 
# here the name attribute returns full name(along with extension) 
# of the input file
print("The File Name Along with Extension is:",Path(inputFilepath).name)

輸出

File Name is: tutorialsPoint
The File Name Along with the Extension is: tutorialsPoint.pdf

方法 3:使用正則表示式(regex 模組)

為了使用特定模式匹配檔名,我們可以使用正則表示式。

pattern - [\w]+?(?=\.)

上述模式分為 3 個模式:

  • [\w] - 匹配集合內的單詞

  • +? - 如果在 ? 關鍵字之前只出現一次,則匹配字串

  • (?=) - 匹配任何字元(不包括換行符),並請記住停止在。

regex re.search() 方法

Python regex re.search() 方法在整個目標字串中搜索 regex 模式的出現,並在找到匹配項的位置返回相應的 Match Object 例項。re.search() 只返回目標字串中第一個與模式匹配的匹配項。

示例

以下程式使用正則表示式從給定的檔案路徑返回檔名:

# importing re(regex) module
import re
# input file path 
inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf'
 
# regex pattern to extract the file name 
regex_pattern = '[\w-]+?(?=\.)'
# searching/matching the pattern of the input file path
result = re.search(regex_pattern, inputFilepath)
# printing the match name
print("The File Name is:",result.group())

輸出

The File Name is: tutorialsPoint

結論

在本文中,我們學習瞭如何使用三種不同的方法從給定的檔案路徑獲取檔名。我們學習瞭如何使用 OS 模組的內建功能修改提供的檔案路徑以滿足我們的需求。

更新於: 2023年1月27日

8K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告