让我们假设,我的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/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
生成目录,子目录和文件的列表。我尝试为我的任务重新构建它,但我只在文件节点上取得进展。
如何为包括目录和子目录在内的所有节点重建它?
答案 0 :(得分:0)
__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'
]
}
]
}
]
}