The central idea : Recursive function
The code is as follows
import os
import os.path
def tree(path, depth=0):
if depth == 0:
print(path)
items = os.listdir(path)
for item in items:
# File and subfolder names in the output folder
print('| '*depth, end='')
print('|----', item)
item = os.path.join(path, item)
if os.path.isdir(item):
# Recursively traverse subdirectories
tree(item, depth+1)
tree(r'E:\pycharm\pycharm2020.3\pycharm2020.3\cjh\learn_code')
Running results