How to delete a file? Getting "The process cannot access the file because it is being used by another process" error

370 views Asked by At

Update: I am not getting the error when hosting this online. Able to delete normally. Leaving this up incase there are any useful answers for running locally on windows pc.

Context: I download a pdf file from discord. Then I read it etc. then I delete it. (I am having to download and delete in first place because reading it directly from discord object was causing me to hit discord's rate limits)

What I have tried till now

  1. simple os.remove()
  2. f.close() then os.remove()
  3. f.close() then renaming the file (with 'temp' suffix) then os.remove()
  4. waiting for the lock to be removed, with asyncio and retrying (retried 100 times in a minute, still was locked)
  5. deleting the folder that contains the file using shutil.rmtree()
  6. changing the directory to some temp using os.chdir() then doing the operation there then changing it back to previous directory, then deleting the temp directory using shutil.rmtree

Everytime the same error WindowsError: [Error 32] The process cannot access the file because it is being used by another process:

In some discord messages I pass multiple pdf files. It does not throw error in deleting the first one, but again throws it in last one.

Here's my code

filepath=os.path.join('downloaded_files', attachment.filename)
print(filepath)
with open(filepath, 'wb') as f:
    f.write(content)
    input_text=pdf_text_from_attachment(filepath)
    to_send=input_text
    
    await send_message_in_thread(
                                channel_id,
                                to_send)
    f.close()
    os.remove(filepath)
1

There are 1 answers

0
Tim Roberts On

This should work:

filepath=os.path.join('downloaded_files', attachment.filename)
print(filepath)
with open(filepath, 'wb') as f:
    f.write(content)

input_text=pdf_text_from_attachment(filepath)
await send_message_in_thread(channel_id, input_text)
os.remove(filepath)