Search code examples
pythoncsvdirectory

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!


Solution

  • 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