使用python生成目录树

来源:http://www.sh-fengwen.com 作者:鲜果干果 人气:81 发布时间:2019-09-04
摘要:复制代码 代码如下: 这是一个使用Python生成文件、目录树的程序,其中遇到一个问题是:如何确定某个目录下的某一文件是最后一个遍历的文件。因为最后一个遍历的文件前应添加"└─

复制代码 代码如下:

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import optparse

# 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 

LOCATION_NONE     = 'NONE'
LOCATION_美高梅游戏平台网站,MID      = 'MID'
LOCATION_MID_GAP  = 'MID_GAP'
LOCATION_TAIL     = 'TAIL'
LOCATION_TAIL_GAP = 'TAIL_GAP'

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

Notations = {
    LOCATION_NONE: '',
    LOCATION_MID: '├─',
    LOCATION_MID_GAP: '│  ',
    LOCATION_TAIL: '└─',
    LOCATION_TAIL_GAP: '    '
}

您可能感兴趣的文章:

  • Python3遍历目录树实现方法
  • python实现目录树生成示例
  • python 生成目录树及显示文件大小的代码

class Node(object):
    def __init__(self, name, depth, parent=None, location=LOCATION_NONE):
        self.name = name
        self.depth = depth
        self.parent = parent
        self.location = location
        self.children = []

    def __str__(self):
        sections = [self.name]
        parent = self.has_parent()
        if parent:
            if self.is_tail():
                sections.insert(0, Notations[LOCATION_TAIL])
            else:
                sections.insert(0, Notations[LOCATION_MID])
            self.__insert_gaps(self, sections)
        return ''.join(sections)

    def __insert_gaps(self, node, sections):
        parent = node.has_parent()
        # parent exists and parent's parent is not the root node
        if parent and parent.has_parent():
            if parent.is_tail():
                sections.insert(0, Notations[LOCATION_TAIL_GAP])
            else:
                sections.insert(0, Notations[LOCATION_MID_GAP])
            self.__insert_gaps(parent, sections)

    def has_parent(self):
        return self.parent

    def has_children(self):
        return self.children

    def add_child(self, node):
        self.children.append(node)

    def is_tail(self):
        return self.location == LOCATION_TAIL

class Tree(object):
    def __init__(self):
        self.nodes = []

    def debug_print(self):
        for node in self.nodes:
            print(str(node) + '/')

    def write2file(self, filename):
        try:
            with open(filename, 'w') as fp:
                fp.writelines(str(node) + '/n'
                              for node in self.nodes)
        except IOError as e:
            print(e)
            return 0
        return 1

本文由美高梅游戏平台网站发布于鲜果干果,转载请注明出处:使用python生成目录树

关键词:

上一篇:使用SAX解析xml(python3.4)

下一篇:没有了

最火资讯