I have about 100 folders with random names, say for this example 1,2,3,4,...100. Inside these folders, I have text files with some strings in them. eg: sample.txt.

The text files all have the same name but are in different folders. What I need is to read the files from inside these folders, and read the text inside these files and print out or save the location of these text files.

I only know how to read lines from a file if it is in my pwd and look for stuff in it. I use the following code for that:

with open(r'Example.txt', 'r') as infile_txt:
    for line in infile_txt:
        if r"sample" in line:
            print line

How can I read files from inside folders and record the names of these folders?

2

There are 2 answers

1
Hisagr On

You can use os for that. For example:

import os
list_downloads = os.listdir("C:/Users/user/Downloads")

This will give you all subfolders and files in a list. You can then traverse the list to find needed subfolder and repeat the action.

0
aabb bbaa On
import os
import re
from os.path import join, getsize

with open('output.txt','w') as out_file:
    for root,subFolders, files in os.walk(r"C:\Users\USER007\Desktop\Python Scripts\Reading metadata\files"):
        if r'MetaData.txt' in files:
            with open(os.path.join(root, 'MetaData.txt'), 'r') as in_file:
                for lines in in_file:
                    if r'THIS' and r'THAT' and r'THOSE' in lines:
                        print root

The above code worked for me.