简体   繁体   English

在子文件夹python中读取所有文件

[英]read all files in a subfolder python

I have a folder structure as 我有一个文件夹结构

>root
  > foldername1
    > subfoldername1
    > subfoldername2
    > subfoldername3
  > foldername2
    > subfoldername1
    > subfoldername2
    > subfoldername3
  > foldername3
    > subfoldername1
    > subfoldername2
    > subfoldername3

I would like to list all the file contained in the 'subfoldername3' of 'foldername2' 我想列出“ foldername2”的“ subfoldername3”中包含的所有文件

I approached the problem as follow, but since I have an incredible number of folders, subfolders, and files it takes forever to come to a conclusion.... is there a fastest way to do the same? 我按照以下方法解决了这个问题,但是由于我拥有数量惊人的文件夹,子文件夹和文件,所以要永远得出结论。...有没有最快的方法来做到这一点?

all_folders = [x[0] for x in walk(root)]
sub_folder = [s for s in all_folders if 'foldername2' in s]
matching_sub_path = [s for s in sub_folder if 'subfoldername3' in s]

matching_sub_path =
//root//foldername2//subfoldername3

I think os.walk will list all directory recursively. 我认为os.walk将递归列出所有目录。

for you case try this if it suits your need. 对于您的情况,请尝试一下是否适合您的需要。

all_folders = [x[0] for x in walk(root)]

all_files = [os.listdir(dir_path)
             for dir_pathin all_folder
                 if "subfoldername3" and "foldername2" in dir_path]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM