我正在写一个Python脚本,可以重命名一个目录中的一堆.WAV文件,并重命名,在文件名的开头加上音频文件的长度。
我现在得到的结果是。
import wave
import contextlib
import os
for file_name in os.listdir(os.getcwd()):
if file_name.endswith(".wav") or file_name.endswith(".aiff"):
with contextlib.closing(wave.open(file_name, 'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
duration = int(duration)
duration = str(duration)
new_file_name = duration + " " + file_name
print(file_name)
os.rename(file_name, new_file_name)
else:
continue
但我得到了这个错误
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'TEMFX01-RisingLong001.wav' -> '15 TEMFX01-RisingLong001.wav'
我怎样才能让这个程序停止使用它来重命名它?
谢谢!谢谢
EDIT:真的很傻,只是需要在print(file_name)之前加上f.close()。
不知道我是应该删除这个主题还是回答我自己的问题?
重命名前关闭wave。
import wave
import contextlib
import os
for file_name in os.listdir(os.getcwd()):
if file_name.endswith(".wav") or file_name.endswith(".aiff"):
with contextlib.closing(wave.open(file_name, 'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
duration = int(duration)
duration = str(duration)
new_file_name = duration + " " + file_name
print(file_name)
wave.close()
os.rename(file_name, new_file_name)
else:
import wave
import contextlib
import os
count = 0
for file_name in os.listdir(os.getcwd()):
if file_name.endswith(".wav") or file_name.endswith(".aiff"):
count += 1
with contextlib.closing(wave.open(file_name, 'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
duration = int(duration)
duration = str(duration)
new_file_name = "audio" + str(count) + '.wav'
print(file_name)
os.rename(file_name, new_file_name)
else:
continue
这个代码可以解决这个问题