os 與 os.path提供跨平台文件系統操作。關鍵函數速查:
| 函數 | 用途 |
|---|---|
os.listdir(dir) | 列出目錄條目(文件+子目錄) |
os.getcwd() | 獲取當前工作目錄 |
os.chdir(path) | 切換工作目錄 |
os.path.isdir(path) | 判斷是否目錄 |
os.path.isfile(path) | 判斷是否文件 |
os.path.exists(path) | 判斷是否存在 |
os.path.getsize(path) | 獲取文件大小(目錄返回 0) |
os.path.join(*paths) | 跨平台路徑拼接 |
os.path.split(path) | 分離 (目錄, 文件名) |
os.path.splitext(path) | 分離 (文件名, 副檔名) |
os.listdir 手寫遞歸(教學用)
import os, sys
def listdir_recursive(dir_path, outfile, indent=0):
prefix = ' ' * indent
outfile.write(f'{prefix}{os.path.basename(dir_path)}/\n')
file_count = 0
for entry in os.listdir(dir_path):
full = os.path.join(dir_path, entry)
if os.path.isdir(full):
file_count += listdir_recursive(full, outfile, indent + 1)
else:
outfile.write(f'{prefix} {entry}\n')
file_count += 1
return file_count
if __name__ == '__main__':
target = input('Please input path: ').strip()
with open('list.txt', 'w', encoding='utf-8') as f:
total = listdir_recursive(target, f)
f.write(f'\nTotal files: {total}\n')
os.walk 內建遞歸(生產首選)
import os
def walk_dir(dir_path, outfile, topdown=True):
for root, dirs, files in os.walk(dir_path, topdown=topdown):
for f in files:
full = os.path.join(root, f)
print(full)
outfile.write(full + '\n')
for d in dirs:
full = os.path.join(root, d)
outfile.write(' ' + full + '\n')
if __name__ == '__main__':
target = input('Please input path: ').strip()
with open('list.txt', 'w', encoding='utf-8') as f:
walk_dir(target, f)
os.walk 關鍵參數topdown=True(預設):先處理父目錄,再遞歸子目錄。可在循環中修改 dirs 列表以剪枝(如跳過 .git、__pycache__)。topdown=False:後序遍歷,先處理最深子目錄,適合底層先刪除的場景。followlinks=False:不跟隨符號鏈接,避免循環。
for root, dirs, files in os.walk(top):
dirs[:] = [d for d in dirs if not d.startswith('.')] # 就地修改 dirs 影響遞歸
for f in files:
process(os.path.join(root, f))
pathlib.Path.rglob(Python 3.4+)
from pathlib import Path
for file in Path('src').rglob('*.py'):
print(file) # Path 物件
print(file.name) # 檔名
print(file.parent) # 父目錄
print(file.stat().st_size) # 大小
os.scandir/os.walk 效能略優。生產代碼首選 os.walk**(或 pathlib.rglob),內建遞歸、剪枝、效能優化。手寫遞歸僅供教學理解原理。掌握 topdown 剪枝技巧,能靈活控制遍歷行為。