我正在尝试创建计算机上存在的目录的json目录树。但我只想包括.exe,.bat,.cmd文件的类型,名称和路径。我在网上找到了它,它可以创建一个完整的目录,但是我只想清除其中的文件类型。
我尝试使用“好词”,但是这破坏了我的json语法并留下了很多开放空间
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
]
except OSError as e:
if e.errno != errno.ENOTDIR:
raise
hierarchy['type'] = 'file'
return hierarchy
if __name__ == '__main__':
try:
directory = sys.argv[1]
except IndexError:
directory = "."
hierarchy = path_hierarchy(r"\mypath\")
with open('myjson.json', 'w') as outfile:
json.dump(hierarchy, outfile, indent=2, sort_keys=True)
good_words = ['.exe', '.cmd', '.bat','},','{','[',']']
with open('myjson.json') as oldfile, open('myjsonfixed.json', 'w') as newfile:
for line in oldfile:
if any(good_word in line for good_word in good_words):
newfile.write(line.replace(dontwant,want))