HOWTO · Python

用 Python 開啟目錄中的所有檔案

使用 os.listdir() 讀取一個目錄中的檔案,使用 glob.glob() 依模式選擇相符項目,使用 os.scandir() 掃描條目,或使用 os.walk() 包含巢狀目錄。

本頁內容

要讀取目錄中的文字檔案,對單一目錄使用 os.listdir(),依模式選擇名稱使用 glob.glob(),檢查條目使用 os.scandir(),包含巢狀目錄使用 os.walk()。用回傳的名稱建立路徑,並在 with 陳述式中使用 open()。這些範例讀取的是文字;二進位檔案需要 "rb" 之類的二進位模式,或針對具體格式的剖析器。

使用 os.walk() 開啟目錄中的檔案

當檔案可能位於起始目錄或其下的任何目錄時,使用 os.walk()。它在每次迭代中產生三個值:目前目錄路徑(root)、其子目錄的名稱(dirnames),以及直接位於該目錄中的檔案的名稱(filenames)。將 root 與每個檔案名連接起來得到路徑;如果只連接起始目錄和檔案名,將會遺漏巢狀目錄中的檔案。

這個範例建立了一個小的目錄樹,因此可以按所寫內容直接執行。對目錄名和檔案名排序,使這個測試夾具的處理順序可以預測;否則目錄的遍歷順序並不保證。

執行這個範例:

import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    nested = os.path.join(directory, "notes")
    os.mkdir(nested)
    for folder, name, contents in [
        (directory, "summary.txt", "Ready"),
        (nested, "details.txt", "More notes"),
    ]:
        with open(os.path.join(folder, name), "w", encoding="utf-8") as file:
            file.write(contents)

    for root, dirnames, filenames in os.walk(directory):
        dirnames.sort()
        for filename in sorted(filenames):
            path = os.path.join(root, filename)
            with open(path, encoding="utf-8") as file:
                print(f"{filename}: {file.read()}")

os.walk() 可以自上而下或自下而上遍歷。預設是自上而下,適合在發現檔案時就處理檔案。這個範例明確使用 UTF-8;請選擇與你的文字檔案相符的編碼。如果檔案使用不同的編碼,應按照格式處理這些檔案,而不是假設一種編碼適用於所有檔案。對於你的行程無法讀取的目錄,應根據應用程式的需要處理由此產生的檔案系統錯誤。

使用 os.listdir() 開啟目錄中的檔案

os.listdir() 回傳直接位於一個目錄內部的條目的名稱。它不會進入子目錄,其結果可以同時包含檔案和目錄。將每個名稱與目錄路徑連接,並在開啟前檢查 os.path.isfile(),如下所示。

import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    with open(os.path.join(directory, "one.txt"), "w", encoding="utf-8") as file:
        file.write("First file")
    os.mkdir(os.path.join(directory, "archive"))

    for name in sorted(os.listdir(directory)):
        path = os.path.join(directory, name)
        if os.path.isfile(path):
            with open(path, encoding="utf-8") as file:
                print(f"{name}: {file.read()}")

當你想要一個目錄中的每一個常規檔案、且不需要模式比對時,這種方法很有用。os.path.isfile() 檢查會跟隨指向檔案的符號連結;如果你的應用程式必須區分連結或套用不同的政策,應使用適當的路徑或目錄條目檢查。把 with 區塊保留在每個檔案周圍,這樣 Python 會在讀取後關閉它,包括後續處理提前退出該區塊的情況。

使用 glob.glob() 開啟相符的檔案

glob.glob() 使用檔案名模式來選擇路徑。諸如 *.txt 這樣的模式會相符直接位於指定目錄中的文字檔案;它本身不會搜尋子目錄。回傳的路徑可以直接傳遞給 open()。當任務是造訪整棵樹時使用 os.walk(),或者在你需要時有意建立遞迴模式。

import glob
import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    for name, contents in [("readme.txt", "Instructions"), ("data.csv", "id")]:
        with open(os.path.join(directory, name), "w", encoding="utf-8") as file:
            file.write(contents)

    pattern = os.path.join(directory, "*.txt")
    for path in sorted(glob.glob(pattern)):
        with open(path, encoding="utf-8") as file:
            print(f"{os.path.basename(path)}: {file.read()}")

變更模式的最後一個組成部分,以選擇不同的檔案名集合,例如 report-*.csv。當後續工作依賴穩定的順序時,對相符項排序很有用。模式也可以相符目錄名,因此如果模式並不限於檔案,應使用 os.path.isfile() 過濾相符的路徑。

使用 os.scandir() 開啟目錄中的檔案

os.scandir() 產生目錄條目物件,這些物件公開每個條目的名稱和路徑,並提供 is_file() 等方法。當迴圈需要在開啟條目之前檢查它、或查看條目資訊時,它很有用。這個迭代器是一個上下文管理器,因此在迭代結束時應使用 with 關閉它。這個範例檢查條目並讀取常規檔案;它不會遞迴進入子目錄。

import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    with open(os.path.join(directory, "notes.txt"), "w", encoding="utf-8") as file:
        file.write("Scanned text")
    os.mkdir(os.path.join(directory, "archive"))

    with os.scandir(directory) as entries:
        for entry in sorted(entries, key=lambda item: item.name):
            if entry.is_file():
                with open(entry.path, encoding="utf-8") as file:
                    print(f"{entry.name}: {file.read()}")

entry.name 是被掃描目錄內的名稱,而 entry.path 是開啟該條目時要使用的路徑。與 os.listdir() 一樣,一次 os.scandir() 呼叫只覆蓋一個目錄。如果條目在檢查和開啟之間可能發生變化,檔案系統狀態可能在這段間隔內改變,因此處理不受信任或同時被修改的目錄的程式碼,也應考慮開啟時的錯誤。

為你的目錄選擇正確的方法

對一個目錄進行簡單的非遞迴遍歷時,選擇 os.listdir()。當應由檔案名模式決定處理哪些路徑時,選擇 glob.glob()。當巢狀目錄中的檔案是任務的一部分時,選擇 os.walk()。當每個條目在你對其採取行動之前都需要檔案檢查或其他條目資訊時,選擇 os.scandir()。

這四種方法都會列舉目錄內容,但列舉順序並不保證;當可重複的處理很重要時,應對名稱或路徑排序。這些範例使用上下文管理的檔案物件和 UTF-8 文字模式。使編碼適應原始檔案,當檔案不是純文字時使用二進位模式或剖析器。存取權限、處理過程中消失的檔案,以及應用程式特有的編碼差異,在生產程式碼中可能需要額外處理。