Delete a file after reading
<p>In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:</p>

<p><code>An error occurred while reading file. [WinError 32] The process cannot access the file because it is being used by another process</code></p>

<p>I'm reading file using <code>with</code>, and I've tried <code>f.close()</code> and also <code>f.closed</code> but its the same error every time.</p>

<p>This is my code:</p>

<pre><code>f = open(filePath)
    with f:
        line = f.readline().strip()
        tempLst = line.split(fileSeparator)

        if(len(lstHeader) != len(tempLst)):
            headerErrorMsg = "invalid headers"
            hjsonObj["Line No."] = 1
            hjsonObj["Error Detail"] = headerErrorMsg
            data['lstErrorData'].append(hjsonObj)
            data["status"] = True

            f.closed
            return data                                                  

    f.closed
</code></pre>

<p>after this code I call the remove function:</p>

<pre><code>os.remove(filePath)
</code></pre>

<p><strong>Edit:</strong> using <code>with open(filePath) as f:</code> and then trying to remove the file gives the same error. </p>

<p>This</p>

<pre><code>import os

path = 'path/to/file'

with open(path) as f:
  for l in f:
    print l,

os.remove(path)
</code></pre>

<p>should work, with statement will automatically close the file after the nested block of code</p>

<p>if it fails, File could be in use by some external factor. you can use Redo pattern.</p>

<pre><code>while True:
  try:
    os.remove(path)
    break
  except:
    time.sleep(1)
</code></pre>

python file