List contents of directories in a tree-like format

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   2014   

  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個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.