プログラミング素人のはてなブログ

プログラミングも電気回路も専門外の技術屋の末端が勉強したことや作品をアウトプットするブログ。コードに間違いなど見つけられたら、気軽にコメントください。 C#、Python3、ラズパイなど。

Pythonでファイル・フォルダ構造を出力する

Windowsの検索が使いにくい

Windowsにはファイル検索Boxがありますが、挙動が期待と違うことが多くあります。
自動的に検索範囲が制限されているのが原因らしいです。
www.pasoble.jp

そこでファイル・フォルダ構造をすべて出力するスクリプトを作ってみました。
カレントフォルダ(もしくはコメントアウトした部分に指定するフォルダ)を基準として、その下層のフォルダ・ファイル構造を出力します。

アルゴリズムとしては、現在フォルダから下層にあるものをファイルとフォルダに分けて、ファイルはいったんリストに追加しまとめて出力。フォルダはキューに追加して、キューが空になるまでカレントフォルダを移動してファイルのリストを出力していきます。
フォルダのアクセスは幅優先探索的になります。

import os
import glob
import queue
import datetime

q = queue.Queue()


# os.chdir(r"C:\\Users\\xxxx\\Pictures")
d = os.getcwd()
q.put(d)
filename = 'output.txt'
output = open(filename, 'a', encoding='utf')  # 書き込みモードでオープン
output.write(str(datetime.datetime.now()))
output.write("\n")
output.close()


def wfs(wd):
    try:
        files = glob.glob(wd+"/*")
        list = []
        for f in files:
            if not os.path.isfile(f):
                q.put(f)
            else:
                index = f.rfind("\\")+1
                f = f[index:]
                list.append(f)
        print("")
        print(wd)
        print(list)
        output = open(filename, 'a', encoding='utf')  # 書き込みモードでオープン
        output.write("\n"+wd+"\n")
        output.write(str(list))
        output.write("\n")
        output.close()
    except Exception as e:
        print(e)


while not q.empty():
    wfs(q.get())

output = open(filename, 'a', encoding='utf')  # 書き込みモードでオープン
output.write("\n")