user2718886
user2718886

Reputation: 5

Finding many strings in directory

I have a directory full of files and a set of strings that need identification(about 40). I want to go through all of the files in the directory and print out the names of the files that have any one of my strings. I found code that works perfectly (Search directory for specific string), but it only works for one string. Whenever I try to add more, it prints out the name of every single file in the directory. Can someone help me tweak the code as I just started programming a few days ago and don't know what to do.

import glob
for file in glob.glob('*.csv'):
    with open(file) as f:
        contents = f.read()
    if 'string' in contents:
        print file

That code was taken from the question I mentioned above. Any help would be appreciated and any tips on asking the question better would as well! Thank You!

Upvotes: 0

Views: 169

Answers (3)

d_k
d_k

Reputation: 25

You could use a generator together with any, which short-circuits on the first True:

import glob

myStrings = ['str1', 'str2']
for file in glob.glob('*.csv'):
    with open(file) as f:
        contents = f.read()
        
    if any(string in contents for string in myStrings):
        print file
        
    

Upvotes: 0

Blender
Blender

Reputation: 298364

I would just use grep:

$ grep -l -f strings.txt *.csv

Upvotes: 0

Bonifacio2
Bonifacio2

Reputation: 3850

You can try:

import glob
strings = ['string1', 'string2']
for file in glob.glob('*.csv'):
    with open(file) as f:
        contents = f.read()
    for string in strings:
        if string in contents:
            print file
            break

About asking better questions: link

Upvotes: 1

Related Questions