title: Python reload textfile into string every x seconds in a loop
body: <p>I am trying to read a text file into a string, do something with the string, then ever X seconds, 
  re-read the text file (in case it has changed) to update the string and do the same thing again, over and over in a loop, without spawning an infinite number of processes.</p>
  
  <p>so something like :</p>
  
  <p>in an infinite loop
   open 'MyTextFile' and read it into a String
   do stuff with the string of text it reads from the file
   close the file (if I need to...to allow another script to write to it)
  wait x seconds before clearing the string and re-reading the 
  same 'MyTextFile' file to update the string and do it all again
  (in an infinite loop until I tell it to stop)</p>
  
  <p>What would be a good sturdy (reliable to run for a long time) way to do that?</p>
  
  <p>Thanks!</p>
  
  <pre><code>&lt;code&gt;
  import os
  import time
  
  myDataFile = "MyData.txt"
  data = ""
  
  def ReadFile(data):
      # only need to read it if data has changed
      # detect 'modified' date of myDataFile and only PrintToPrinter IF it has change
      # and if it has NOT changed, wait 10 seconds and check again
      # IF CHANGED
              with open (myDataFile, "r") as myFile:
                      try:
                              data=myFile.read().replace('\n', '  ')
                      finally:
                              myFile.close()
                  ShowOnScreen(data)
                  PrintToPrinter(data)
      # ELSE 
          # data has not changed..
          # no need to print it so I shouldn't send back to PrintToPrinter
          # but I still want to ShowOnScreen(data) on screen
          # and keep the program running to check for changes
          ShowOnScreen(data)
          sleep(10)
          ReadFile(data)
  
  def ShowOnScreen(data):
          print(time+' '+data)
  
  def PrintToPrinter(data):
      # send DateTimeStamp+data to printer here
      # go back to checking for changes
      ReadFile(data)
  
  # kick off the program to start looking for changes
  # data starts out as "" so it should always read the first time
  # and send to printer and screen
  ReadFile(data)
  &lt;/code&gt;
  </code></pre>