遍历文件夹,然后遍历子文件夹并打印带有文本文件路径的文件名 [英] Iterate through folders, then subfolders and print filenames with path to text file

查看:19
本文介绍了遍历文件夹,然后遍历子文件夹并打印带有文本文件路径的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 创建批量运行其他软件所需的文件.为此,我需要生成一个文本文件,将所需的数据文件加载到软件中.我的问题是我需要输入到这个文本文件中的文件存储在一组结构化文件夹中.

I am trying to use python to create the files needed to run some other software in batch. For part of this I need to produce a text file that loads the needed data files into the software. My problem is that the files I need to enter into this text file are stored in a set of structured folders.

我需要遍历一组文件夹(最多 20 个),每个文件夹最多可以包含另外 3 个文件夹,其中包含我需要的文件.文件夹的底层包含每次运行软件所需的一组文件.文本文件应逐行打印这些文件的路径+名称,添加指令行,然后从文件夹移至下一组文件,依此类推,直到检查完所有子级文件夹.

I need to loop over a set of folders (up to 20), which each could contain up to 3 more folders which contain the files I need. The bottom level of the folders contain a set of files needed for each run of the software. The text file should have the path+name of these files printed line by line, add an instruction line and then move to the next set of files from a folder and so on until all of sub level folders have been checked.

推荐答案

使用 os.walk().下面将输出dir"子目录中所有文件的列表.结果可以根据您的需要进行处理:

Use os.walk(). The following will output a list of all files within the subdirectories of "dir". The results can be manipulated to suit you needs:

import os                                                                                                             
                                                                                                                      
def list_files(dir):                                                                                                  
    r = []                                                                                                            
    subdirs = [x[0] for x in os.walk(dir)]                                                                            
    for subdir in subdirs:                                                                                            
        files = os.walk(subdir).next()[2]                                                                             
        if (len(files) > 0):                                                                                          
            for file in files:                                                                                        
                r.append(os.path.join(subdir, file))                                                                         
    return r                                                                                                          

对于 python 3,将 next() 更改为 __next__().

For python 3, change next() to __next__().

这篇关于遍历文件夹,然后遍历子文件夹并打印带有文本文件路径的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆