python 3すべてのファイルとフォルダを巡回

833 ワード

データを処理する際には、ディレクトリの下のすべてのフォルダ、またはすべてのディレクトリのファイルを巡回する必要があり、pythonが持参したosと再帰的に巡回するのが一般的である.walk()メソッド、次にosについて説明します.walk()の実用化
1.すべてのディレクトリ名を巡り、すべてのディレクトリパスを保存するtxtテキスト
import os
"""
       
"""
fn = open('dir.txt','w')

for root,dirs,files in os.walk(r"D:\code\test"):
    for dir in dirs:#     
        dirPath =os.path.join(root, dir) #      
        fn.write(dirPath + '
') fn.close()

2.すべてのファイル名を巡り、パスをつなぎ、ファイルパスをテキストに保存する
import os
"""
              
"""
fn = open('files.txt','w')

for root,dirs,files in os.walk(r"D:\code\test"):
    for f in files:#     
        dirPath =os.path.join(root, f) #       
        fn.write(dirPath + '
') fn.close()