Skip to content

Instantly share code, notes, and snippets.

@wiredrawing
Last active January 17, 2017 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wiredrawing/18ba9cde4e33c663db74f02b7aef30fa to your computer and use it in GitHub Desktop.
Save wiredrawing/18ba9cde4e33c663db74f02b7aef30fa to your computer and use it in GitHub Desktop.
Windows向け:特定のディレクトリ以下のディレクトリおよびファイルの一覧を取得する。 ref: http://qiita.com/1000VICKY/items/00a1c79f72f9717df7df
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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment