简体   繁体   中英

Reading a text file from within a folder and saving the name of the folder if a particular string is found in the text file - Python

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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