使用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任意字符串转16, 32, 64进制的方法

Python字符串转数字 import binascii s = 'test123456test' str_16 = binascii.b2a_hex(s.encode...

Python和GO语言实现的消息摘要算法示例

Python和GO语言实现的消息摘要算法示例

常用的消息摘要算法有MD5和SHA,这些算法在python和go的库中都有,需要时候调用下就OK了,这里总结下python和go的实现。 一、python消息摘要示例 代码如下: 复制代...

python3+PyQt5实现柱状图

python3+PyQt5实现柱状图

本文通过Python3+pyqt5实现了python Qt GUI 快速编程的16章的excise例子。 #!/usr/bin/env python3 import random...

django drf框架自带的路由及最简化的视图

django-drf框架自带的路由以及最简化的视图,具体内容如下所示: 路由 一.导入模块 from rest_framework.routers import SimpleRout...

windows下安装python的C扩展编译环境(解决Unable to find vcvarsall.bat)

windows下安装python的C扩展编译环境(解决Unable to find vcvarsall.bat)

N久没有开始写博客了,总觉得要随便记点东西,岁月蹉跎,曾经搞得一些东西、技术、工具,说丢也就丢了,点点滴滴还是要记录一下吧。。。    在windows下使用pip安装一些python的...