python實(shí)現(xiàn)目錄樹(shù)生成示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import optparse
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: ' '
}
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
def build(self, path):
self.__build(path, 0, None, LOCATION_NONE)
def __build(self, path, depth, parent, location):
if os.path.isdir(path):
name = os.path.basename(path)
node = Node(name, depth, parent, location)
self.add_node(node)
if parent:
parent.add_child(node)
entries = self.list_folder(path)
end_index = len(entries) - 1
for i, entry in enumerate(entries):
childpath = os.path.join(path, entry)
location = LOCATION_TAIL if i == end_index else LOCATION_MID
self.__build(childpath, depth + 1, node, location)
def list_folder(self, path):
"""Folders only."""
return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
# for entry in os.listdir(path):
# childpath = os.path.join(path, entry)
# if os.path.isdir(childpath):
# yield entry
def add_node(self, node):
self.nodes.append(node)
def _parse_args():
parser = optparse.OptionParser()
parser.add_option(
'-p', '--path', dest='path', action='store', type='string',
default='./', help='the path to generate the tree [default: %default]')
parser.add_option(
'-o', '--out', dest='file', action='store', type='string',
help='the file to save the result [default: pathname.trees]')
options, args = parser.parse_args()
# positional arguments are ignored
return options
def main():
options = _parse_args()
path = options.path
if not os.path.isdir(path):
print('%s is not a directory' % path)
return 2
if not path or path == './':
filepath = os.path.realpath(__file__) # for linux
path = os.path.dirname(filepath)
tree = Tree()
tree.build(path)
# tree.debug_print()
if options.file:
filename = options.file
else:
name = os.path.basename(path)
filename = '%s.trees' % name
return tree.write2file(filename)
if __name__ == '__main__':
import sys
sys.exit(main())
運(yùn)行效果
gtest_start/
├─build/
├─lib/
│ └─gtest/
├─output/
│ ├─primer/
│ │ ├─Debug/
│ │ │ ├─lib/
│ │ │ └─obj/
│ │ └─Release/
│ │ ├─lib/
│ │ └─obj/
│ └─thoughts/
│ ├─Debug/
│ │ ├─lib/
│ │ └─obj/
│ └─Release/
│ ├─lib/
│ └─obj/
├─src/
│ ├─primer/
│ └─thoughts/
├─test/
│ ├─primer/
│ └─thoughts/
├─third_party/
│ └─gtest/
└─tools/
相關(guān)文章
python?rpyc客戶端調(diào)用服務(wù)端方法的注意說(shuō)明
這篇文章主要介紹了python?rpyc客戶端調(diào)用服務(wù)端方法的注意說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
利用python計(jì)算windows全盤(pán)文件md5值的腳本
這篇文章主要介紹了利用python計(jì)算windows全盤(pán)文件md5值的腳本,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
使用Rasterio讀取柵格數(shù)據(jù)的實(shí)例講解
今天小編就為大家分享一篇使用Rasterio讀取柵格數(shù)據(jù)的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
一篇文章帶你了解谷歌這些大廠是怎么寫(xiě) python 代碼的
這篇文章主要介紹了谷歌這些大廠怎么寫(xiě)python代碼,我們寫(xiě)代碼,往往還是按照其它語(yǔ)言的思維習(xí)慣來(lái)寫(xiě),那樣的寫(xiě)法不僅運(yùn)行速度慢,代碼讀起來(lái)也費(fèi)盡,給人一種拖泥帶水的感覺(jué),需要的朋友可以參考下2021-09-09
Python讀取ZIP和TAR格式壓縮包的實(shí)現(xiàn)
本文介紹了使用Python讀取ZIP和TAR格式的壓縮包,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
Python 中將秒轉(zhuǎn)換為小時(shí)、分鐘和秒的示例代碼
這篇文章主要介紹了在 Python 中將秒轉(zhuǎn)換為小時(shí)、分鐘和秒,本篇文章將討論使用 Python 中的四種不同方法來(lái)使用、管理秒并將其轉(zhuǎn)換為天、小時(shí)、分鐘和秒,需要的朋友可以參考下2023-05-05
Python圖像處理之透視變換的實(shí)戰(zhàn)應(yīng)用
透視變換(Perspective Transformation)是將圖片投影到一個(gè)新的視平面(Viewing Plane),也稱作投影映射(Projective Mapping),下面這篇文章主要給大家介紹了關(guān)于Python圖像處理之透視變換的相關(guān)資料,需要的朋友可以參考下2021-08-08

