欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python 遍历子文件和所有子文件夹的代码实例

时间:2021-04-10 08:52:59|栏目:Python代码|点击:

最近看ECShop到网上找资料,发现好多说明ECShop的文件结构不全面,于是想自己弄个出来。但这是个无聊耗时的工作,自己就写了个Python脚本,可以递归遍历目录下的所有文件和所有子目录,并将结果记录到一个.xml文件中(因为想使用Notepad++的代码折叠功能,所以使用.xml文件)。

下面就是Python代码:

# -*- coding: cp936 -*- 
 
############################################# 
#  Written By Qian_F            #    
#  获取文件路径列表,并写入到当前目录生成test.txt # 
############################################# 
 
import os 
 
def getfilelist(filepath, tabnum=1): 
  simplepath = os.path.split(filepath)[1] 
  returnstr = simplepath+"目录<>"+"\n" 
  returndirstr = "" 
  returnfilestr = "" 
  filelist = os.listdir(filepath) 
  for num in range(len(filelist)): 
    filename=filelist[num] 
    if os.path.isdir(filepath+"/"+filename): 
      returndirstr += "\t"*tabnum+getfilelist(filepath+"/"+filename, tabnum+1) 
    else: 
      returnfilestr += "\t"*tabnum+filename+"\n" 
  returnstr += returnfilestr+returndirstr 
  return returnstr+"\t"*tabnum+"</>\n" 
       
 
path = raw_input("请输入文件路径:") 
usefulpath = path.replace('\\', '/') 
if usefulpath.endswith("/"): 
  usefulpath = usefulpath[:-1] 
if not os.path.exists(usefulpath): 
  print "路径错误!" 
elif not os.path.isdir(usefulpath): 
  print "输入的不是目录!" 
else: 
  filelist = os.listdir(usefulpath) 
  o=open("test.xml","w+") 
  o.writelines(getfilelist(usefulpath)) 
  o.close() 
  print "成功!请查看test.xml文件" 

执行该Python脚本后会在当前目录生成test.xml文件,使用Notepad++打开(以ANSI编码方式)就可以看到指定目录的文件结构了。下面是我生成的ECShop下upload目录的文件结构部分截图:

上一篇:jupyter notebook oepncv 显示一张图像的实现

栏    目:Python代码

下一篇:Python hashlib和hmac模块使用方法解析

本文标题:Python 遍历子文件和所有子文件夹的代码实例

本文地址:http://www.codeinn.net/misctech/98479.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有