如何使用 Python 查詢檔案?


在龐大的程式設計世界中,Python 憑藉其適應性和流行性脫穎而出。它易於使用且可靠,使其成為各領域開發人員的首選。對於程式設計師來說,在他們的機器上查詢檔案是一項常見任務。無論您是在整理資料、分析日誌還是開發檔案管理解決方案,在 Python 中查詢檔案都是一項必備技能。

在本文中,我們將探討多種 Python 檔案查詢策略和方法。我們將討論傳統方法和更高階的方法,並提供詳細的解釋,以確保您完全理解這些概念。

在此過程中,我們將提供一些程式碼示例,展示各種檔案搜尋技術,以便您可以選擇最適合您特定用例的方法。

讓我們開始這段激動人心的 Python 檔案探索之旅吧!

使用 os.walk() 進行目錄遍歷

os.walk() 方法是 Python 中遍歷目錄的主要方法之一。它允許我們從給定路徑開始遍歷目錄樹,從而查詢包含在該路徑中的所有檔案和子目錄。

示例

  • 匯入 os 模組,它提供了各種作業系統功能,例如管理檔案和目錄。

  • 函式 find_files_with_os_walk() 接受兩個引數:search_path(開始搜尋的目錄路徑)和 target_extension(要查詢的副檔名)。

  • 在函式內部,我們建立一個名為 found_files 的空列表,用於儲存與指定副檔名匹配的檔案的路徑。

  • os.walk() 函式遍歷目錄樹,每次迭代返回當前根目錄、其子目錄列表和其檔案列表。

  • 使用巢狀迴圈檢查每個檔案的副檔名,如果它與 target_extension 匹配,則將其完整路徑新增到 found_files 列表中。

import os

def find_files_with_os_walk(search_path, target_extension):
   found_files = []
   for root, dirs, files in os.walk(search_path):
      for file in files:
         if file.endswith(target_extension):
            found_files.append(os.path.join(root, file))
   return found_files

使用 glob.glob() 進行更簡單的檔案搜尋

glob 模組是另一個有用的檔案搜尋工具。它提供 glob.glob() 函式,允許我們使用萬用字元和模式搜尋檔案。

示例

  • 我們匯入 glob 模組,它專注於基於模式的檔案搜尋。

  • 函式 find_files_with_glob() 的 search_pattern 引數指定與檔案匹配的帶萬用字元的模式。

  • glob.glob() 函式使用提供的模式進行搜尋,然後返回一個與模式匹配的檔案路徑列表。

import glob

def find_files_with_glob(search_pattern):
   return glob.glob(search_pattern)

利用 pathlib 進行增強的檔案路徑操作

Python 3.4 引入了 pathlib 模組,它提供了一種面向物件的方法來處理檔案路徑。它簡化了檔案路徑操作,並提供了一個方便的 glob() 方法。

示例

  • 我們從 pathlib 包中匯入 Path 類,它是檔案系統路徑的表示。

  • 在 find_files_with_pathlib() 方法中,我們使用 Path(search_path) 將 search_path 引數轉換為 Path 物件。

  • Path 的 glob() 方法提供模式匹配功能;在這個例子中,我們使用 ** 萬用字元來掃描每個子目錄。

  • 該方法返回一個生成器,因此我們使用 list() 將其轉換為列表,並根據 target_extension 過濾檔案。

from pathlib import Path

def find_files_with_pathlib(search_path, target_extension):
   search_path = Path(search_path)
   return list(search_path.glob(f"**/*.{target_extension}"))

使用 fnmatch.fnmatch() 進行簡化的模式匹配

如果您想要更簡單的模式匹配策略,fnmatch 模組很有用。它提供了 fnmatch.fnmatch() 方法,該方法使用類似於 Unix shell 中的萬用字元來匹配檔名。

示例

  • 為了使用 fnmatch.fnmatch() 方法,我們現在除了 os 模組外還匯入 fnmatch 模組。

  • 方法 find_files_with_fnmatch() 接受兩個引數:target_pattern,一個 Unix shell 風格的萬用字元模式,用於與檔名匹配;search_path,搜尋的起始目錄路徑。

  • 與前面一樣,我們使用 os.walk() 遍歷目錄樹,並使用 fnmatch.fnmatch() 方法根據 target_pattern 過濾檔案。

import os
import fnmatch

def find_files_with_fnmatch(search_path, target_pattern):
   found_files = []
   for root, dirs, files in os.walk(search_path):
      for file in files:
         if fnmatch.fnmatch(file, target_pattern):
            found_files.append(os.path.join(root, file))
   return found_files

使用 os.scandir() 方法提高效能

為了更有效地掃描目錄,Python 提供了 os.scandir() 方法,該方法在 Python 3.5 中引入。它返回一個迭代器,其中包含有關每個檔案條目的附加資訊,對於大型目錄,它比 os.walk() 更快。

示例

  • 在這個例子中,我們仍然使用 os 模組,但是為了獲得更快的目錄迭代器,我們使用 os.scandir() 而不是 os.walk()。

  • find_files_with_os_scandir() 方法接受與前面示例相同的兩個引數:target_extension 和 search_path(搜尋的起始目錄路徑)。

  • 為了確保正確的資源管理,我們使用 with 語句,在 with 塊內,我們迴圈遍歷 os.scandir() 迭代器。

  • 如果每個條目的名稱符合 target_extension 並且它是一個檔案,我們將它的完整路徑附加到 found_files 列表中。

import os

def find_files_with_os_scandir(search_path, target_extension):
   found_files = []
   with os.scandir(search_path) as entries:
      for entry in entries:
         if entry.is_file() and entry.name.endswith(target_extension):
            found_files.append(entry.path)
   return found_files

結論

在這篇詳盡的文章中,我們介紹了多種使用 Python 查詢檔案的方法。每種方法都有其優點,從傳統的 os.walk() 用於目錄遍歷到現代的 os.scandir() 用於提高效率。此外,我們還討論了使用 pathlib 進行面向物件的檔案路徑操作的便捷性,以及 glob 和 fnmatch 簡化的模式匹配功能。

現在您掌握了這些知識,就可以在您的 Python 應用程式中輕鬆處理各種檔案搜尋場景。您可以根據目錄的大小和搜尋的複雜性選擇最有效的方法以獲得最佳結果。

繼續練習和探索 Python 生態系統,您將繼續提高在這門多功能語言中的程式設計技能。

更新於:2023年8月22日

2K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.