現在のフォルダーとそのすべてのサブフォルダーを参照して、.htm|.html 拡張子を持つすべてのファイルを取得したいと思います。次のようにして、オブジェクトが dir かファイルかを確認できることがわかりました。
import os
dirList = os.listdir("./") # current directory
for dir in dirList:
if os.path.isdir(dir) == True:
# I don't know how to get into this dir and do the same thing here
else:
# I got file and i can regexp if it is .htm|html
そして最終的には、すべてのファイルとそのパスを配列に含めたいと思います。そのようなことは可能ですか?
ベストアンサー1
使用できますos.walk()
ディレクトリとそのすべてのサブディレクトリを再帰的に反復処理します。
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith((".html", ".htm")):
# whatever
これらの名前のリストを作成するには、リストの内包表記を使用できます。
htmlfiles = [os.path.join(root, name)
for root, dirs, files in os.walk(path)
for name in files
if name.endswith((".html", ".htm"))]