[英]Can't close temporary files made with the Python tempfile module
我正在使用一个名为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, bitrate=options['bitrate'], format='mp3')
await ctx.send(file=discord.File(final)) # sends the file to a Discord chat
我不确定我在这里缺少什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.