Pythonで子フォルダからファイルを検索するサンプル
環境
Python 3.9.7
書式
os.walk(top=’フォルダパス’, topdown=False):
引数topに対象のフォルダを指定します
引数 topdown=False を指定し、子フォルダから検索しています
使用例
import os
for root, dirs, files in os.walk(top='C:\data2', topdown=False):
for file in files:
filePath = os.path.join(root, file)
print(f'filePath: {filePath}')
for dir in dirs:
dirPath = os.path.join(root, dir)
print(f'dirPath: {dirPath}')
実行結果
>python test.py filePath: C:\data2\11\logging-copy.txt filePath: C:\data2\22\cft_mod.csv filePath: C:\data2\test.doc filePath: C:\data2\test02.xls dirPath: C:\data2\11 dirPath: C:\data2\22