Possible Duplicate:
Search for string in txt file Python
How, in python, can I delete a file if it contains a string.
I want it to go though all files in a directory, open them, check if they contain a string, if yes, deletes the file and moves onto the next one.
There are a few pieces to this problem. First, you need a listing of the files. Depending on your needs:
glob.glob,os.listdiroros.walkmight 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: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.removeoros.unlinkto delete the file ifcheck_file_for_stringreturnsTrue.