python递归输出目录列表

博客第一篇,python学得有点乱,今天用它实现了递归输出目录列表

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Fri Jan  8 15:52:02 2021
 4 
 5 @author: Administrator
 6 """
 7 
 8 import os
 9 
10 def listdirs(path,result):
11     if os.path.isfile(path):
12         dirname = os.path.dirname(path)
13         if dirname not in result:
14             result[dirname] = [path]
15         else:
16             result[dirname] += [path]
17     elif os.path.isdir(path):
18         subdirs = os.listdir(path)
19         for subdir in subdirs:
20             cur_path = os.path.join(path, subdir)
21             listdirs(cur_path,result)
22             
23 if __name__ == "__main__":
24     
25     path = r"E:\python"
26     result = dict({})
27     listdirs(path,result)
28     
29     filename = 'e:\dir.txt'
30     with open(filename,'w+') as f:
31         for key,value in result.items():
32             print("dir: " + key)
33             f.write("dir: " + key + "\n")
34             for idx,val in enumerate(value):
35                 print("---file-" + repr(idx) + ": " + val)
36                 f.writelines("---file-" + repr(idx) + ": " + val + "\n")
View Code

 

posted @ 2021-01-08 17:45  数据攻城师  阅读(82)  评论(0)    收藏  举报