发生异常:PermissionError [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:

Exception has occurred: PermissionError [WinError 32] The process cannot access the file because it is being used by another process:

当我 运行 我的代码时出现以下错误(错误发生在 *** 行):

Exception has occurred: PermissionError
[WinError 32] The process cannot access the file because it is being used by another process: 'pexels-joshua-woroniecki-9073157.mp4' #this file is one of two files found in my stockFootage directory

我正在尝试删除一个文件,但它告诉我权限错误。有谁知道我该如何解决这个问题?任何帮助将不胜感激。谢谢。

我的代码:

chdir(r'C:\Users\jack_l\Documents\REDDIT_TO_YOUTUBE_PYTHON_SELENIUM\redditVideo\stockFootage')
myStockFootage = next(walk(r'C:\Users\jack_l\Documents\REDDIT_TO_YOUTUBE_PYTHON_SELENIUM\redditVideo\stockFootage'), (None, None, []))[2]
stockFootage = VideoFileClip(myStockFootage[0], target_resolution=(1080, 1920))
stockFootage = stockFootage.without_audio()
stockFootage = stockFootage.loop(duration = mergedVideos.duration)
stockFootage.write_videofile('loopedStock.mp4', fps = 30)

for counter24 in range(len(myStockFootage)):
    if 'loopedStock' not in myStockFootage[counter24]:
***     os.remove(myStockFootage[counter24])

chdir(r'C:\Users\jack_l\Documents\REDDIT_TO_YOUTUBE_PYTHON_SELENIUM\redditVideo\finalVideo')
finalVideo = CompositeVideoClip([stockFootage, commentVideo])
finalVideo.write_videofile('finalVideo.mp4', fps=30)

print('Finished')

从评论中可以清楚地看出,您要么没有共享导致实际问题的代码,要么所做的更改比评论中建议的更多。

拿这个:

from shutil import copy
from os import remove
import moviepy.video.io.VideoFileClip as VideoFileClip

copy('test.mp4', 'new_test.mp4')
stock_footage = VideoFileClip.VideoFileClip(r'new_test.mp4', target_resolution=(1080, 1920))
try:
    remove('new_test.mp4')
except PermissionError:
    print('as expected')
stock_footage .close()
try:
    remove('new_test.mp4')
    print('success')
except PermissionError:
    print('you will not see this')

输出(假设您在与脚本相同的位置有一个 test.mp4):

as expected
success

这表明 VideoFileClip 锁定了它打开的文件并对其调用 .close() 解决了问题。