最近在学python,写了一个小脚本,基本功能就是遍历显示指定路径下的所有文件夹、文件,根据层级在显示内容前面加"--"。
但是不管怎么样,输出只有第一层的所有文件和文件夹,仔细的审查了好几遍代码,就是找不出原因在哪,求大神告知问题所在,以下是代码内容:
import os rootpath = input("请输入目录:") catedir = os.listdir(rootpath) def prt_dir_files(catedir, is_indent=True, level=0): print(rootpath) for each_item in catedir: if os.path.isdir(each_item): print(each_item) prt_dir_files(os.listdir(each_item), is_indent, level+1) else: if is_indent: print("--" * level, end="") print(each_item) prt_dir_files(catedir)
The key problem is that the path is wrong.
listdir
What we get is only thefile nameunder the directory, not thepath of the file.So you must use
os.path.join
to create a complete path.I changed your code based on the above instructions:
It’s also a good idea to use
os.walk
, as shown below:Questions I answered: Python-QA
os.path.isdir(each_item):
There is a problem with the usage of this function