gpt4 book ai didi

python - 在Python中识别文件系统中的根文件夹

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:16 25 4
gpt4 key购买 nike

我有一个递归方法,可以遍历文件系统结构并从中创建字典。这是代码:

def path_to_dict(path):
d = {'name': os.path.basename(path)}
if os.path.isdir(path):
d['type'] = "directory"
d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
d['children'] = [path_to_dict(os.path.join(path, x)) for x in os.listdir\
(path)]
else:
d['type'] = "file"
d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
with open(path, 'r', encoding="utf-8", errors='ignore') as myfile:
content = myfile.read().splitlines()
d['content'] = content

此时,它会检查它是否是一个文件夹,然后输入键 nametypepathchildren 其中 children 是一个可以包含更多文件夹或文件的数组。如果它是一个文件,则具有键 nametypepathcontent。转成JSON后,最终的结构是这样的。

{
"name": "nw",
"type": "directory",
"path": "Parsing/nw",
"children": [{
"name": "New folder",
"type": "directory",
"path": "Parsing/nw/New folder",
"children": [{
"name": "abc",
"type": "directory",
"path": "Parsing/nw/New folder/abc",
"children": [{
"name": "text2.txt",
"type": "file",
"path": "Parsing/nw/New folder/abc/text2.txt",
"content": ["abc", "def", "dfg"]
}]
}, {
"name": "text2.txt",
"type": "file",
"path": "Parsing/nw/New folder/text2.txt",
"content": ["abc", "def", "dfg"]
}]
}, {
"name": "text1.txt",
"type": "file",
"path": "Parsing/nw/text1.txt",
"content": ["aaa "]
}, {
"name": "text2.txt",
"type": "file",
"path": "Parsing/nw/text2.txt",
"content": []
}]

}

现在我希望脚本始终仅将根文件夹中的type 设置为值root。我怎样才能做到这一点?

最佳答案

我认为您想要与以下实现类似的东西。根文件夹中的目录和文件将包含 "type": "root" 并且子元素不会包含此键值对。

def path_to_dict(path, child=False):
d = {'name': os.path.basename(path)}
if os.path.isdir(path):
if not child:
d['type'] = "root"
d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
d['children'] = [path_to_dict(os.path.join(path, x), child=True) for x in os.listdir\
(path)]
else:
if not child:
d['type'] = "root"
d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
with open(path, 'r', encoding="utf-8", errors='ignore') as myfile:
content = myfile.read().splitlines()
d['content'] = content

关于python - 在Python中识别文件系统中的根文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56242708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com