简体   繁体   中英

How do I search all text files in directory for a string and place the found result in a text file in Python

I am trying to write some Python code that looks at all.txt files in a directory and for any file that contains a specific string, will append the file name to a.txt file.

I currently have the following code that works when I select a single file:

 with open('FW_ (Big) Data Engineer.msg datatext.txt') as f:
    if "Data Engineer" in f.read():
        f = open("Data Engineer.txt","a+")
        f.write("Found it, but I would rather have the file name here")
        f.close() 

Let's say the directory path is "C:\Users\me\textfiles", I can't seem to find a way to loop through all files in that directory, look for the string and write the name of the file into for instance "Data Engineer.txt" if it should belong there.

I have tried defining my path as a variable but I haven't found a working solution (tried os.scandir and Path) and I haven't found a working solution to loop through all files in this directory. I know that f.write needs a string but I thought that placing the variable between str() would solve this problem.

Try this:

import os

# Remember to change these
directory = "test";
text = "Test";
def search(dirname):
    array = [];
    for i in os.listdir(dirname):
        i = os.path.join(dirname, i);
        if(os.path.isdir(i)):
            x = search(i);
            if(not x):
                continue;
            array = array + x;
        else:
            if(text in open(i, "r").read()):
                do_something();
search(directory);

This will also search in subdirectories.

You can iterate trough a folder with the following code:

import os

for filename in os.listdir(directory):
    with open (directory+'/'+filename) as f:
        #your code here

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