如何删除文件?收到“该进程无法访问该文件,因为该文件正在被另一个进程使用”错误

问题描述 投票:0回答:1

更新:我在线托管时没有收到错误。可以正常删除。保留这个以防万一有任何在 Windows 电脑上本地运行的有用答案。

上下文:我从discord下载了一个pdf文件。然后我读了它等等,然后我删除了它。 (我必须首先下载并删除,因为直接从不和谐对象读取它导致我达到不和谐的速率限制)

到目前为止我已经尝试过的事情

  1. 简单的 os.remove()
  2. f.close() 然后 os.remove()
  3. f.close() 然后重命名文件(带有“temp”后缀)然后 os.remove()
  4. 等待解除锁,用asyncio并重试(一分钟重试100次,仍然被锁)
  5. 使用shutil.rmtree()删除包含该文件的文件夹
  6. 使用 os.chdir() 将目录更改为某个临时目录,然后在那里执行操作,然后将其更改回以前的目录,然后使用shutil.rmtree删除临时目录

每次都出现同样的错误 WindowsError:[错误 32] 该进程无法访问该文件,因为该文件正在被另一个进程使用:

在一些不和谐消息中,我传递了多个 pdf 文件。它在删除第一个时不会抛出错误,但在最后一个时又会抛出错误。

这是我的代码

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)
python discord discord.py file-handling os.path
1个回答
0
投票

这应该有效:

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)
© www.soinside.com 2019 - 2024. All rights reserved.