利用pathlib库进行路径读取,然后递归进行搜索
import os, re, json, copy
from pathlib import Path, PurePath
def searchAllFiles(self, path, fileTree={}, initial=True):
if initial:
root = path if isinstance(path, str) else str(path)
fileTree[root] = {}
initial = False
return searchAllFiles(root, fileTree[root], initial)
p = Path(path if isinstance(path, str) else str(path))
dirs = [x for x in p.iterdir() if x.is_dir()]
files = [x for x in p.iterdir() if x.is_file()]
for file in files:
fileTree[file.name] = [file.suffix, file.as_posix()]
for dir in dirs:
fileTree[str(dir.parts[-1])] = {}
searchAllFiles(dir, fileTree[str(dir.parts[-1])], initial)
if __name__ == '__main__':
sampleDir = './test'
fileTree = {}
searchAllFiles(sampleDir, fileTree)
print(fileTree)