LoginSignup
1
2

More than 5 years have passed since last update.

Windows向け:特定のディレクトリ以下のディレクトリおよびファイルの一覧を取得する。

Last updated at Posted at 2017-01-16

ちょっと、捜し物をしたくて
WindowsPCの端末のディレクトリを一斉走査するスクリプトを書きました。

下記、スクリプトの(1)の
python
mainDirList = os.listdir();

上記の引数に、対象のディレクトリを指定して実行するだけで
ユーザーディレクトリに一覧を書き出すように処理を書いています。
そのうちアップデートするかもしれません。

import os
from io import StringIO
from io import BytesIO
import datetime


#ioオブジェクトの作成
#出力内容をバッファリングする
i = StringIO()
#実行時のディレクトリを取得
path = os.getcwd()

#スキャン開始元ディレクトリ(1)
mainDirList = os.listdir("C:\\")

separate = "\\"
tab = "    "

def checkAllData(fileName, path, fp, tab = "    "):

    """当該関数に渡された第一引数がディレクトリの場合のみ実行"""
    """この場合、一旦プロセスを停止して、当該のディレクトリを再帰的にスキャン"""
    if os.path. isdir(path) == True:
        fp.write(tab + fileName + "\n")
        directoryList = os.listdir(path)
        for __temp__ in directoryList :
            if os.path.isdir( path + separate + __temp__) == True:
                """親ディレクトリを出力"""
                fp.write(tab + __temp__ + "\n");
                res = (checkAllData(__temp__, path + separate + __temp__, fp, tab + "    "));
            else:
                fp.write(tab + "->" +__temp__ + "\n")
    else :
        """当該関数に渡された第一引数がファイルの場合、そのまま出力"""
        fp.write(tab + "->" + fileName + "\n")


"""ディレクトリ構造をファイルへ書き込み"""
try:
    #スキャンしたディレクトリ一覧をファイルへ出力する。
    fp = open("C:\\Users\\太郎\\test.dat", "w", encoding="CP932")

    #ディレクトリのスキャン開始
    for tempLine in mainDirList:
        try:
            """現在のディレクトリ階層をループ"""
            path = "C:" + separate + tempLine
            if os.path.exists(path):
                fp.write(tempLine + "\n");
                checkAllData(tempLine, path, fp, "    " )
            else :
                fp.write("->" + tempLine + "\n");
        except Exception as e:
            print(str(e))
        except :
            fp.write("握り潰す" + "\n");
    fp.close()
except Exception as e:
    print(str(e))
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2