Repetitve seach and replace on constantly changing file. Python
Question: So I'm trying to have a script that will run every 3 seconds to read a text
file, clean it up and write is as another text file. The original text file is
always changing. It's from a music playout program, current song title. I went
collecting bits of python code around the internet and personalizing them to
my needs. Right now I have a script that will work perfectly,each command and
the scheduling. But when the original file changes again, then the script
gives an error. Any idea how this could be fixed?

    
    
    Traceback <most recent call last>:
    File "radio_script.py", line 29, in <module>
       executeSomthing<>
    File "radio_script.py", line 10, in executeSomething
      for line in intext:
    IoError: [Errno 9] Bad file descriptor
    

I'm running the python script on Windows. So when the script is run, if a line
contains any of the "delete_lin" words the whole line is deleted. While each
of the "line replace" entries replace those words with nothing, just as they
are supposed to. Here is my script.

    
    
    # -*- coding: utf-8 -*-
    delete_lin = ['VP', 'VH', 'VT', 'VB', 'VS', 'BG']
    import time
    import os
    def executeSomething():
        with open('current.txt', 'r') as intext, open('currentedit.txt', 'w') as outfile:
           for line in intext:
             if not any(delete_lin in line for delete_lin in delete_lin):
               line = line.replace('(email)', "")                           
               line = line.replace('_AO VIVO', "")
               line = line.replace('Ao Vivo', "")
               line = line.replace('AO VIVO', "")
               line = line.replace('(04)', "")
               line = line.replace('2016', "")
               line = line.replace('2015', "")
               line = line.replace('2014', "")
               line = line.replace('2013', "")
               outfile.write(line)
               outfile.flush()
               intext.flush()
               print 'Pause'
               time.sleep(3)
    
    while True:
        executeSomething()
    


Answer: When the original file is modified, the file reference `intext` is no longer a
valid file. While the path is the same, the actual file has been modified.
Thus, you should call `intext.close()` at the end of the `for` loop. To make
sure it is actually recreating the file reference make sure to only `sleep`
outside the loop.

