python - 一个结构化显示文件的脚本,迭代是否有问题?
阿神
阿神 2017-04-18 09:12:57
0
3
334

最近在学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)
阿神
阿神

闭关修行中......

reply all (3)
大家讲道理

The key problem is that the path is wrong.listdirWhat we get is only thefile nameunder the directory, not thepath of the file.

So you must useos.path.jointo create a complete path.

I changed your code based on the above instructions:

import os def prt_dir(path, indent_symbol='', level=0): print(indent_symbol*level, os.path.basename(path)) if os.path.isdir(path): for f in os.listdir(path): fpath = os.path.join(path, f) prt_dir(fpath, indent_symbol, level+1) if __name__ == '__main__': rootpath = input("请输入目录:") prt_dir(rootpath, '--', 0)

It’s also a good idea to useos.walk, as shown below:

import os def prt_dir(rootpath, symbol=''): for root, dirs, files in os.walk(rootpath): path = root.split('/') print((len(path) - 1) * symbol, os.path.basename(root)) for file in files: print(len(path) * symbol, file) if __name__ == '__main__': rootpath = input("请输入目录:") prt_dir(rootpath, '--')

Questions I answered: Python-QA

    Ty80

    os.path.isdir(each_item):
    There is a problem with the usage of this function

      刘奇
      import os def prt_dir_files(rootpath, is_indent=True, level=0): print(rootpath) catedir = os.listdir(rootpath) for each_item in catedir: if os.path.isdir(rootpath+"/"+each_item): print(each_item) prt_dir_files(rootpath+"/"+each_item, is_indent, level+1) else: if is_indent: print("--" * level, end="") print(each_item) rootpath = input("请输入目录:") prt_dir_files(rootpath)
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!