There are a few pieces to this problem. First, you need a listing of the files. Depending on your needs: glob.glob
, os.listdir
or os.walk
might be appropriate. You also need to know how to open a file and search for the string. The easiest (naive) way to do this is to open the file, read all the contents and check if the string is present:
def check_file_for_string(filename,string):
with open(filename) as fin:
return string in fin.read()
This naive way isn't ideal as it will read the entire contents of your file into memory which could be a problem if the files are really big.
Finally, you can use os.remove
or os.unlink
to delete the file if check_file_for_string
returns True
.