List Files and Directory Tree Structure in Python Posted on 2018-12-16 | Visitors: 123456789101112131415161718192021222324252627282930313233343536import osdef walk(path): l = [] file_dir_list = os.listdir(path) if not file_dir_list: return [] for item in file_dir_list: if os.path.isfile(path + "\\" + item): l.append(item) else: l += walk(path + "\\" + item) return ldef dfs_show_dir(path, depth): if depth == 0: print("root: [" + path + "]") for item in os.listdir(path): print("| " * depth + "+--" + item) new_item = path + "/" + item if os.path.isdir(new_item): dfs_show_dir(new_item, depth + 1)if __name__ == "__main__": path = os.getcwd() os.chdir("C:\\Users\\lixiang\\PycharmProjects\\other\\testcase_for_walk") path = os.getcwd() print(walk(path), "\n") dfs_show_dir(path, 0) 123456789['4.txt', '5.txt', '6.txt'] root: [C:\Users\lixiang\PycharmProjects\other\testcase_for_walk]+--1| +--2| +--3| | +--4.txt| | +--5.txt| +--6.txt