title: Python:The process cannot access the file because it is being used by another process
body: <pre><code>try:
      masterpath = os.path.join(path, "master.txt") 
      with open(masterpath, 'r') as f:
          s = f.read()
      f.close()
      exec(s)
      with open(masterpath, 'w') as g:
          g.truncate()
      g.close()
      os.remove(masterpath)
  </code></pre>
  
  <p>Here I want to read something in a .txt file and then erase content and delete it. But it always shows it cannot delete it as 'The process cannot access the file because it is being used by another process'.<br>
  Actually what I need is to delete the .txt file, but it cannot delete immediately sometimes, so I erase the content at first in case that it will be read again. So is there any good way to read something in a .txt file and then delete this file as soon and stable as possible?</p>