在Python中标识文件系统中的根文件夹
我有一个递归方法,它遍历文件系统结构并从中创建字典。 代码如下:在Python中标识文件系统中的根文件夹,python,Python,我有一个递归方法,它遍历文件系统结构并从中创建字典。 代码如下: 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[
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
此时,它检查它是否是一个文件夹,然后将键name
,type
,path
和children
放入其中,其中children
是一个可以包含更多文件夹或文件的数组。如果它是一个文件,则具有键名称
、类型
、路径
和内容
。
将其转换为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": []
}]
}
现在,我希望脚本总是将仅根文件夹中的
类型设置为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
我认为您需要类似于以下实现的东西。根文件夹中的目录和文件将包含“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
您不需要向我们展示所有不相关的代码和输出。看看如何创建一个。做你想做的吗?@PeterWood,谢谢,我以后会记住的。你不需要向我们展示所有不相关的代码和输出。看看如何创建一个。做你想做的吗?@PeterWood,谢谢,我以后会记住的。