python 精练(1)
短信预约 -IT技能 免费直播动态提醒
#/usr/bin/python env
from os import listdir , sep
from os.path import abspath, basename, isdir
from sys import argv
def tree(dir, padding, print_files=False):
print padding[:-1] + '+-' + basename(abspath(dir)) + '/'
padding = padding + ' '
files = []
if print_files:
files = listdir(dir)
else:
files = [ x for x in listdir(dir) if isdir(dir + sep +x)]
count = 0
for file in files:
count +=1
print padding + '|'
path = dir + sep + file
if isdir(path):
if count == len(files):
tree(path, padding + ' ', print_files)
else:
tree(path, padding + '|', print_files)
else:
print padding + '+-' + file
def usage():
return '''Usage: %s [-f] <path>
print tree structure of path specified.
options:
-f print files as well as directories
path path to process''' % basename(argv[0])
def main():
if len(argv) == 1:
print usage()
elif len(argv) == 2:
path = argv[1]
if isdir(path):
tree(path, ' ')
else:
print 'ERROR: \'' + path + '\' is not a diretory'
elif len(argv) == 3 and argv[1] == '-f':
path = argv[2]
if isdir(path):
tree(path, ' ', True)
else:
print 'ERROR: \'' + path + ' \' is not a dirctory'
else:
print usage()
if __name= '__main__':
main()
#较长的代码必须要有main()主方法。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341