全てのフォルダとファイルを取得
import os
for root, dirs, files in os.walk(top='./targetDir'):
for dir in dirs:
dirPath = os.path.join(root, dir)
print(f'dirPath = {dirPath}')
for file in files:
filePath = os.path.join(root, file)
print(f'filePath = {filePath}')
-
3行目: 引数 top に 対象のフォルダを指定します。戻り値は次の通りです。
変数名 変数の型 内容 root 文字列 検索中のパス ※1 dirs 文字列リスト root 内にあるディレクトリ名のリスト files 文字列リスト root 内にあるファイル名のリスト - 5行目: os.path.join 関数で 検索中のパス と ディレクトリ名 を結合しています。
- 9行目: 検索中のパス と ファイル名 を結合しています。ファイルのパスを組み立てるとき、dirs 変数の内容を結合する必要はありません。
全てのファイルのみ取得
ファイルのみ処理したい場合、dirs変数 は必要ありません。import os
for root, dirs, files in os.walk(top='./targetDir'):
for file in files:
filePath = os.path.join(root, file)
print(f'filePath = {filePath}')
全てのフォルダのみ取得
フォルダのみ処理したい場合、files変数 は必要ありません。import os
for root, dirs, files in os.walk(top='./targetDir'):
for dir in dirs:
dirPath = os.path.join(root, dir)
print(f'dirPath = {dirPath}')
拡張子を指定して検索
文字列オブジェクト の lower関数 と endswith関数 を利用します。lower関数 で アルファベットを小文字に統一し、endswith関数 でファイル名の末尾を調べます。 endswith関数は 引数に渡した値 と 文字列の末尾 が一致すると True を返します。複数の拡張子を調べたい場合は タプル(tuple) で指定します。拡張子が '.txt' と '.csv' のファイルを探す
import os
for root, dirs, files in os.walk(top='./targetDir'):
for file in files:
if not file.lower().endswith(('.txt', '.csv')):
continue
filePath = os.path.join(root, file)
print(f'filePath = {filePath}')
検索中フォルダの階層(深さ)を取得
文字列オブジェクト の count関数 で パス区切り文字 の個数を数えます。'/' は Unix、'\\' は Windows です。import os
target = './targetDir'
for root, dirs, files in os.walk(top=target):
deps = (root.count('/') + root.count('\\')) - (target.count('/') + target.count('\\'))
print(f'階層 = {deps}')
子フォルダ -> 親フォルダ の順番で取得
通常は 親フォルダ -> 子フォルダ -> 孫フォルダ の順序で一覧を返しますが、 引数 topdown=False を指定すると 孫フォルダ から走査されます。例えば、ファイルとフォルダを全て削除したい場合などに役立ちます。サブフォルダ から ファイルを列挙
import os
for root, dirs, files in os.walk(top='./targetDir', 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}')
- 3行目: 引数 topdown=False を指定し、子フォルダから検索しています。
サブフォルダ内の走査が不要な場合
次の記事を参照してください。検証環境
- Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
- Python 3.9.7 (default, Sep 3 2021, 20:10:26) [GCC 10.2.1 20210110] on linux
- Docker image: python
- Docker Desktop 4.0.1(68347)
- Docker Engine 20.10.8
- Docker Compose 1.29.2
- Microsoft Windows 10 Pro Version 21H1 OS Build 19043.1237 Experience: Windows Feature Experience Pack 120.2212.3530.0