首頁  >  文章  >  後端開發  >  如何在 Python 中高效找到檔案:os.walk 與模式匹配指南

如何在 Python 中高效找到檔案:os.walk 與模式匹配指南

Patricia Arquette
Patricia Arquette原創
2024-10-28 08:35:29864瀏覽

 How to Efficiently Find Files in Python: A Guide to os.walk and Pattern Matching

在Python 中尋找檔案

定位檔案可能具有挑戰性,特別是當它的位置在不同的使用者電腦上不同時。不用擔心,Python 為這個難題提供了一個解決方案 - os.walk 函數。

os.walk() 有兩個參數:您要搜尋的目錄的路徑和為每個目錄呼叫的函數、子目錄和遇到的檔案。

尋找第一個符合

要尋找與提供的名稱相符的第一個文件,請使用以下程式碼:

<code class="python">import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)</code>

尋找所有符合條件

如果您想要尋找所有符合特定名稱的文件,請使用下列程式碼:

<code class="python">def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result</code>

符合模式

要根據模式匹配文件,請使用以下程式碼片段:

<code class="python">import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

find('*.txt', '/path/to/dir')</code>

透過這些方法,您可以輕鬆地找到任何目錄中的文件,使文件管理變得輕而易舉,無論它們如何變化地點。

以上是如何在 Python 中高效找到檔案:os.walk 與模式匹配指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn