首页 > 代码库 > List contents of directories in a tree-like format
List contents of directories in a tree-like format
Python programming practice.
Usage: List contents of directories in a tree-like format.
#!/usr/bin/python#Author: lxw0109#Date: 20140719#Usage: List contents of directories in a tree-like format.import osimport sysdef tree(directory, count): if os.path.isdir(directory): print((count + 1) * "| " + "|---" + os.path.basename(directory)) # Get the file/directory list in ‘dir‘ dirFormat = os.listdir(directory) dirFormat.sort() for dirItem in dirFormat: #absPath = os.path.abspath(dirItem) #NO: On most platforms, this is equivalent to calling the function normpath() as follows: #normpath(join(os.getcwd(), path)) absPath = directory + os.sep + dirItem tree(absPath, count + 1) else: print((count + 1) * "| "+ "|---" + os.path.basename(directory))def main(): #print(sys.argv) #NOTE: sys.argv is a list. if len(sys.argv) != 2: print("Usage: tree DirectoryName") sys.exit(0) #directory = "/home/lxw/Documents/Programing" directory = sys.argv[1] #Get rid of the ‘/‘ at the end. if directory.endswith(os.sep): directory = directory[:-1] #turn Relative Path / Absolute Path into Absolute Path. if directory[0] != ‘/‘: #print("RELATIVE: " + directory[0]) directory = os.getcwd() + os.sep + directory #print("direcotry: " + directory) #count = directory.count(os.sep) tree(directory, -1)if __name__ == "__main__": main()
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。