无法关闭使用 Python tempfile 模块制作的临时文件

问题描述

我正在使用一个名为 pydub 的基于 ffmpeg 的模块来编辑音频文件。我正在尝试使用模块 tempfile,但由于某种原因我无法关闭文件(它们没有被删除)。使用上下文管理器时,它会抛出 PermissionError

我的尝试:

代码按预期工作,但不会删除临时文件,也不会引发错误

temp1,temp2 = tempfile.NamedTemporaryFile(dir='data/temp',delete=False),None
# save something to temp1
seg = AudioSegment.from_file_using_temporary_files(temp1)

if options['overlay']:
    # create new seg
    if overlay_seg:
        temp2 = tempfile.NamedTemporaryFile(dir='data/temp',delete=False)
        # save something to temp2
        overlay_seg = AudioSegment.from_file_using_temporary_files(temp2)
        seg = seg.overlay(overlay_seg)

# edit the audio more here..

final = 'data//temp//edited.mp3'
seg.export(final,bitrate=options['bitrate'],format='mp3')
await ctx.send(file=discord.File(final)) # sends the file to a discord chat
temp1.close()
if temp2:
    temp2.close()

这将创建第一个临时文件,然后抛出一个错误

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\python38\lib\site-packages\discord\ext\commands\core.py",line 85,in wrapped
    ret = await coro(*args,**kwargs)
  File "<myfile>",line 153,in editaudio
    await attachment.save(temp1.name)
  File "C:\Users\User\AppData\Local\Programs\Python\python38\lib\site-packages\discord\message.py",line 155,in save
    with open(fp,'wb') as f:
PermissionError: [Errno 13] Permission denied: '<base>data\\temp\\tmpnf2r68qe'
with tempfile.NamedTemporaryFile(dir='data/temp') as temp1: 
    await attachment.save(temp1.name)
    seg = AudioSegment.from_file_using_temporary_files(temp1)
    if options['overlay']:
        # create new seg
        if overlay_seg:
            with tempfile.NamedTemporaryFile(dir='data/temp') as temp2:
                # save something to temp2
                overlay_seg = AudioSegment.from_file_using_temporary_files(temp2)
                seg = seg.overlay(overlay_seg)

    # edit the audio more here..

    final = 'data//temp//edited.mp3'
    seg.export(final,format='mp3')
    await ctx.send(file=discord.File(final)) # sends the file to a discord chat

我不确定我在这里缺少什么

解决方法

好吧,如果您使用选项 delete=False 创建临时文件,则它们不会被删除。这是不言自明的,但也在 docs 中提到。

您的第二种方法很难调试,因为您没有提供 minimal reproducible example。大概出现问题是因为您已经使用上下文管理器打开了临时文件。 attachment.save() 可能需要一个路径,但我在网上找不到文档。