gpt4 book ai didi

python - 如何使用 os.listdir 按第一个目录排序,然后在 python 中使用文件?

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:56 26 4
gpt4 key购买 nike

我使用os.listdir(),这段代码可以遍历系统目录结构,然后生成一个json文件给easyui的django前端调用display tree UI:

def CreateDirTree(path,file_json):
global id_num
id_num=0
def createDict(path):
global id_num
tree_list=[]
pathList = os.listdir(path)
for i,item in enumerate(pathList):
id_num+=1
children_map={}
children_map['id']=id_num
children_map['text']=item
if os.path.isdir(os.path.join(path,item)):
path = os.path.join(path,item)
print "directory:",path
tmp_listdir=os.listdir(path)
if len(tmp_listdir) != 0:
children_map['state']='closed'
children_map['children'] = createDict(path)
tree_list.append(children_map)
path = '\\'.join(path.split('\\')[:-1])
else:
tree_list.append(children_map)
print children_map
return tree_list

tree_list=createDict(path)
fjson = json.dumps(tree_list,ensure_ascii=False,sort_keys=False)
with open(file_json,'w') as lf:
lf.write(fjson)
##end
CreateDirTree("D:\\all_source\\somesite","123.json")

运行结果为:

directory: D:\all_source\somesite\a

file is: b.txt

file is: oo.txt

file is: a.txt

directory: D:\all_source\somesite\b

file is: 123.txt

file is: b.txt
directory: D:\all_source\somesite\c

file is: yyt.txt

directory: D:\all_source\somesite\c\z

file is: c.txt

file is: e.txt

但是我要的效果是:

directory: D:\all_source\somesite\a

a subdir files: 123.txt

a subdir files: abc.txt

directory: D:\all_source\somesite\b

directory: D:\all_source\somesite\c

directory: D:\all_source\somesite\c\z

file is: a.txt

file is: b.txt

file is: c.txt

file is: e.txt

先按目录排序再按文件排序,怎么办?请帮助我,谢谢!

最佳答案

为目录创建一个列表,为文件创建另一个列表,并迭代它们的连接。根据您的代码进行调整:

(...)
# List of directories only
dirlist = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
# List of files only
filelist = [x for x in os.listdir(path) if not os.path.isdir(os.path.join(path, x))]
for i,item in enumerate(dir_list + filelist):
(...)

这将从目录及其子目录开始,然后移动到文件

关于python - 如何使用 os.listdir 按第一个目录排序,然后在 python 中使用文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29922801/

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