Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a file after reading

Tags:

python

file

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:

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

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

This is my 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

after this code I call the remove function:

os.remove(filePath)

Edit: using with open(filePath) as f: and then trying to remove the file gives the same error.

like image 276
Tahreem Iqbal Avatar asked Sep 10 '16 07:09

Tahreem Iqbal


1 Answers

Instead of:

 f.closed

You need to say:

f.close()

closed is just a boolean property on the file object to indicate if the file is actually closed.

close() is method on the file object that actually closes the file.

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.

like image 102
selbie Avatar answered Sep 23 '22 07:09

selbie