In Python, Implementing "tree" Command. Recursively Traverse All Files And Folders.

import os
import sys

def tree(path):
    if not os.path.exists(path):
        print('Path does not exists:', path)
        return
    elif os.path.isdir(path):
        dir = path
        for path in os.listdir(dir):
            tree(os.path.join(dir, path))
    else:
        print('File name:', path)
        with open(path,'r') as file:
            try:
                print('File contents:')
                for line in file:
                    print(line, end='')
                print('End of file:',path)
            except UnicodeDecodeError:
                print('Cannot read binary file!')
            except IOError:
                print('Something went wrong!')

if '__main__' == __name__:
    path = os.getcwd()
    if 1 < len(sys.argv):
        path = sys.argv[1]
    tree(path)

Download

Comments

Popular posts from this blog