Python 如何从文件创建嵌套字典?
假设我的fs中有这样的结构:Python 如何从文件创建嵌套字典?,python,django,file,python-2.7,directory-structure,Python,Django,File,Python 2.7,Directory Structure,假设我的fs中有这样的结构: Directory --name.txt --content.html --Subdirectory ----name.txt ----content.html ------SubSubDirectory --------name.txt --------content.html 在输出中,我希望: content(Directory/name.txt):path(Directory/content.html) --content(Directory/SubDir
Directory
--name.txt
--content.html
--Subdirectory
----name.txt
----content.html
------SubSubDirectory
--------name.txt
--------content.html
在输出中,我希望:
content(Directory/name.txt):path(Directory/content.html)
--content(Directory/SubDirectory/name.txt):path(Directory/SubDirectory/content.html)
----content(Directory/SubDirectory/SubSubDirectory/name.txt):path(Directory/SubDirectory/SubSubDirectory/content.html)
我有一个功能:
def getffdirs(rootdir):
dir = {}
rootdir = rootdir.rstrip(os.sep)
console.log(rootdir)
start = rootdir.rfind(os.sep) + 1
console.log(start)
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.sep)
shpfiles = {}
for file in files:
if file.endswith(".txt"):
if readFile(os.path.join(path, file)) != '':
full_path = os.path.join(path, file).replace("name.txt", "index.html")
# shpfiles[readFile(os.path.join(path, file))] = os.path.join(path, file)
shpfiles[full_path] = readFile(os.path.join(path, file))
if file.endswith(".html"):
shpfiles['content'] = readFile(os.path.join(path, file))
subdir = dict.fromkeys(shpfiles)
parent = reduce(dict.get, folders[:-1], dir)
parent[folders[-1]] = subdir
return dir
它生成目录、子目录和文件的列表。我尝试为我的任务重新建模,但我只在文件节点上取得了进展
如何为所有节点(包括目录和子目录)重建它
__author__ = 'pranav'
import sys
import os
from os.path import isfile
import json
try:
myname = sys.argv[1]
except Exception, e:
print "usage : python [listfile.py] [foldername]"
exit(1)
def getName(myname):
file_folder_dict = {myname: []}
if not isfile(myname):
try:
for f in os.listdir(myname):
subfolder = os.path.join(myname, f)
file_folder_dict[myname].append(getName(subfolder))
except:
print "No DIR"
else:
return myname
return file_folder_dict
file_folder_dict = getName(myname)
print file_folder_dict
我确实是在很久以前作为一种爱好写这个剧本的。它实际上以dict格式提供所有文件和文件夹。这应该对你有帮助
结果:
{
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/': [
{
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/some1': [
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/some1/some1.txt',
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/some1/some1.html',
{
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/some1/some2': [
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/some1/some2/some2.html',
'/home/likewise-open/PUNESEZ/pranav.ambhore/stack_o_list_files/some1/some2/some2.txt'
]
}
]
}
]
}
您试图构建的字典中的键和值是什么?键可以是当前文件夹的列表[content(name.txt),path(content.html)],值-子文件夹的嵌套字典。也可以是元组,因为不推荐将该列表用作字典中的键。不幸的是,这是一个线性结构。我需要字典或元组相互嵌套,以便以后在浏览器窗口中将其显示为节点。这里的逻辑更复杂(我很难处理):您需要进入目录并查看-是否有扩展名为.txt的文件,如果有:提取此文件的内容并用此内容替换当前目录的名称。之后,向前移动到子目录并执行相同的操作。