Pythonで指定したディレクトリ配下のディレクトリ名とファイル名を取得する(改定案)
http://statsbeginner.hatenablog.com/entry/2015/11/26/134250
import os def gen_filelists(path, abspath=False, sysfile=False): # 指定ディレクトリの配下にあるディレクトリやファイルをたどる for dirpath, dirnames, files in os.walk(path): # sysfile=False の場合、システムディレクトリ(.ではじまるもの)を対象外にする for dir in dirnames: if sysfile==False: if dir.startswith('.'): dirnames.remove(dir) for file in files: # sysfile=False の場合、システムファイル(.ではじまるもの)を無視 if sysfile==False: if file.startswith('.'): pass else: # フルパスを出力するかどうかで処理を分岐 if abspath==True: yield os.path.abspath(file) else: yield file # 下記パートが重複している点、カッコ悪いので改善が必要… else: if abspath==True: yield os.path.abspath(file) else: yield file if __name__ == "__main__": print("abspath:False / sysfile:False") print([ file for file in gen_filelists('.', abspath=False, sysfile=False) ]) # sysfile=True にした場合、Windowsでは os.path.abspath() が . で始まるフォルダを上手く扱えない? print("abspath:False / sysfile:True") print([ file for file in gen_filelists('.', abspath=False, sysfile=True ) ]) print("abspath:True / sysfile:False") print([ file for file in gen_filelists('.', abspath=True, sysfile=False) ]) print("abspath:True / sysfile:True") print([ file for file in gen_filelists('.', abspath=True, sysfile=True ) ])