-3

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.

Community
  • 1
  • 1
Jeremy
  • 319
  • 1
  • 5
  • 17

1 Answers1

4

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.

mgilson
  • 283,004
  • 58
  • 591
  • 667