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>Instead of:</p>

<pre><code> f.closed
</code></pre>

<p>You need to say:</p>

<pre><code>f.close()
</code></pre>

<p><code>closed</code> is just a boolean property on the file object to indicate if the file is actually closed.</p>

<p><code>close()</code> is method on the file object that actually closes the file.</p>

<p>Side note: attempting a file delete after closing a file handle is not 100% reliable. The file might still be getting scanned by the virus scanner or indexer.  Or some other system hook is holding on to the file reference, etc...  If the delete fails, wait a second and try again.</p>

python file