使用python生成目录树

yipeiwu_com5年前Python基础

这是一个使用Python生成文件、目录树的程序,其中遇到一个问题是:如何确定某个目录下的某一文件是最后一个遍历的文件。因为最后一个遍历的文件前应添加"└─",非最后一个文件前添加"├─"。看了Python的API文档没有找到相关的系统函数。现在做法是:先统计出某个目录下的文件个数,在遍历目录时,当个数相等时,就可以确定该目录遍历结束。

# encoding: utf-8  
  
import os   
class dir(object):   
  def __init__(self):   
    self.SPACE = ""   
    self.list = []  
    
  def getCount(self, url):  
    files = os.listdir(url)  
    count = 0;  
    for file in files:  
      myfile = url + "//" + file  
      if os.path.isfile(myfile):  
        count = count + 1  
    return count  
  def getDirList(self, url):   
    files = os.listdir(url)   
    fileNum = self.getCount(url)  
    tmpNum = 0  
    for file in files:   
      myfile = url + "//" + file   
      size = os.path.getsize(myfile)   
      if os.path.isfile(myfile):   
        tmpNum = tmpNum +1  
        if (tmpNum != fileNum):  
          self.list.append(str(self.SPACE) + "├─" + file + "/n")  
        else:  
          self.list.append(str(self.SPACE) + "└─" + file + "/n")  
      if os.path.isdir(myfile):   
        self.list.append(str(self.SPACE) + "├─" + file + "/n")   
        # change into sub directory  
        self.SPACE = self.SPACE + "│ "   
        self.getDirList(myfile)   
        # if iterator of sub directory is finished, reduce "│ "   
        self.SPACE = self.SPACE[:-4]   
    return self.list   
  def writeList(self, url):   
    f = open(url, 'w')   
    f.writelines(self.list)   
    print "ok"   
    f.close()   
if __name__ == '__main__':   
  d = dir()   
  d.getDirList("c:/windows") # input directory  
  d.writeList("c:/1.txt") # write to file 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python with关键字,上下文管理器,@contextmanager文件操作示例

本文实例讲述了Python with关键字,上下文管理器,@contextmanager文件操作。分享给大家供大家参考,具体如下: demo.py(with 打开文件): # ope...

详解Python学习之安装pandas

详解Python学习之安装pandas

一、python pip的安装与使用 1、pip 是 Python 包管理工具,该工具提供了对Python 包的查找、下载、安装、卸载的功能。 目前如果你在 python.or...

对python 读取线的shp文件实例详解

如下所示: import shapefile sf = shapefile.Reader("E:\\1.2\\cs\\DX_CSL.shp") shapes = sf.shapes(...

在Python中用get()方法获取字典键值的教程

 get()方法返回给定键的值。如果键不可用,则返回默认值None。 语法 以下是get()方法的语法: dict.get(key, default=None) 参数...

python 3.5实现检测路由器流量并写入txt的方法实例

python 3.5实现检测路由器流量并写入txt的方法实例

前言 本文主要给大家介绍了关于利用python 3.5检测路由器流量并写入txt的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍。 环境交代:win10+pyth...