Python - How to list all the files

在 Python 開發中,遞迴列出目錄及子目錄下的所有檔案是常見需求。本文分享如何使用內建的 glob 模組,透過簡潔的通配符語法快速取得完整檔案清單。這是一篇掌握檔案系統操作與目錄遍歷技巧的實用技術隨筆。

發佈
閱讀
約 1 分鐘
字數
269
⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。

Sometimes, we need to list all the files in a folder or sub folder in Python.

In this post, I will show you how to use the glob function to achieve this.

Solution

First, let’s take a look at the file structure of the example.

1
2
3
4
5
6
7
8
9
10
./data
├── level-0-0
│   └── file-0.txt
├── level-0-1
│   ├── file-1.txt
│   └── file-2.txt
├── level-0-2
├── file-3.txt
├── file-4.txt
├── file-5.txt

List all the files in single current folder

Now, we can do this by the following code.

1
2
3
4
import glob
files = glob.glob('./data/*.txt')
for file in files:
print(file)

Here is the output.

1
2
3
./data/file-5.txt
./data/file-4.txt
./data/file-3.txt

List all the files in folder recursively

However, we also can list all the files recursively.

1
2
3
4
import glob
files = glob.glob('./data/**/*.txt', recursive=True)
for file in files:
print(file)

Now, we can see all the files in data folder.

1
2
3
4
5
6
./data/file-5.txt
./data/file-4.txt
./data/file-3.txt
./data/level-0-1/file-2.txt
./data/level-0-1/file-1.txt
./data/level-0-0/file-0.txt

Tips

Also, we can use regex with glob

1
2
3
4
import glob
files = glob.glob('./data/**/*[2-3].txt', recursive=True)
for file in files:
print(file)
1
2
./data/file-3.txt
./data/level-0-1/file-2.txt

🙂

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟