Delete results of a grep search across files
Question: I have a script which ultimately should grep a chunk of a text from a file and
delete it, then repeat this for every file in a directory. But the code I've
written below does not include the delete statement because I'm not sure how
to do that. [This post](http://stackoverflow.com/questions/4357499/python-
delete-in-a-string) makes me think I should instead grep everything I want to
keep and write that to a new file instead. I tried inserting `del p` after the
`p = re.compile(ur'(.)(\D\D\D\D\D..........)')` line and that seemed to delete
one of my input files. Suggestions?

    
    
    import sys
    import re 
    import os
    
    
    PSGDirectory = "~/TestFolder"
    
      for path, dirs, files in os.walk(PSGDirectory):
        print path
        print dirs
        print files
    
      def process (files):
        p = re.compile(ur'(.)(\D\D\D\D\D..........)')
        return re.search(p, files)
    
      for root, dirs, files in os.walk(PSGDirectory):
        for filename in files:
            fullpath = os.path.join(root,filename)
            print process (fullpath)
    


Answer: Use re.sub()

From the [Docs:](https://docs.python.org/2/library/re.html)

    
    
    import os
    import re
    
    def process(file):
        with open(file, 'w') as f:
            text = f.read()
            # Use your regex to grab all matching text:
            # For example, to remove all non-digits from a string:
            filtered = re.sub(r'\D', "", text)
            f.write(filtered)
            return filtered
    
    def main():
        PSGDirectory = "~/TestFolder"
        for path, dirs, files in os.walk(PSGDirectory):
            print path
            print dirs
            print files
        for root, dirs, files in os.walk(PSGDirectory):
            for filename in files:
                fullpath = os.path.join(root, filename)
                print process(full path)
    

