0
我有一个脚本将列出所有文件夹和子文件夹并创建一个JSON文件。我想要的只是包含名为“地图”或“报告”列出的子文件夹的文件夹。如果他们包含这些,那么只有父文件夹将被列出,所以“地图”,“报告”将不会显示。目前停留在如何完成这一点,任何帮助将是伟大的。Python列表只包含特定子文件夹的文件夹
import os, json, sys
reload(sys)
sys.setdefaultencoding('utf-8')
path = "G:\Testfolders"
def get_list_of_dirs(path):
try:
output_dictonary = {}
list_of_dirs = [os.path.join(path, item) for item in os.listdir(path) if os.path.isdir(os.path.join(path, item)) and os.path.isdir("./Maps") and os.path.isdir("./Reports")]
output_dictonary["text"] = path.decode('latin1')
output_dictonary["type"] = "directory"
output_dictonary["children"] = []
for dir in list_of_dirs:
output_dictonary["children"].append(get_list_of_dirs(dir))
return output_dictonary
except WindowsError:
pass
print json.dumps(get_list_of_dirs(path))
with open(r'U:\JSONDatatest.json', 'w') as f:
json.dump(get_list_of_dirs(path), f)
编辑:
import os, json, sys
def all_dirs_with_subdirs(path,subdirs):
# make sure no relative paths are returned, can be omitted
try:
output_dictonary = {}
path = os.path.abspath(path)
list_of_dirs = []
for root, dirs, files in os.walk(path):
if all(subdir in dirs for subdir in subdirs):
list_of_dirs.append(root)
return list_of_dirs
output_dictonary["text"] = path.decode('latin1')
output_dictonary["type"] = "directory"
output_dictonary["children"] = []
for dir in list_of_dirs:
output_dictonary["children"].append(all_dirs_with_subdirs(dir))
return output_dictonary
except WindowsError:
pass
with open(r'U:\jsontesting\JSONData.json', 'w') as f:
json.dump(all_dirs_with_subdirs("G:\TESTPATH", ('Maps', 'Temp')), f)
P.S.我知道我没有提到json的东西,我想在json中编码一个unicode符号数组不再是真正的问题了,因为那个部分应该工作atm。 –
谢谢你完美的作品。但是,JSON在拾取该输出列表的父/子树时遇到问题。我曾尝试使用此转换与JSON,但它只是吐出没有孩子等文件夹的列表。我已经将它添加到我的问题。 – Infinity8
太棒了。子子文件夹全部被分组为一个级别的子文件夹。例如G:\ TEST \ a \ b \与G:\ TEST \ a \位于同一级别。有没有办法保留原来的结构? – Infinity8