Reputation: 145
I am trying to convert an mp4 video into an mp3 audio using moviepy then delete the video, the code is as follows:
import moviepy.editor as mp
#converting mp4 to mp3
clip = mp.VideoFileClip("videos/test.mp4")
clip.audio.write_audiofile("test.mp3")
del clip
#delete video file after converting
os.remove("videos/test.mp4")
print("Video Deleted")
This gives the following error PermissionError: [WinError 32] The process cannot access the file because it is being used by another process.
I know I should close the process on the mp4 file in order to close it such as doing with files but isn't del clip
responsible for that ?
Upvotes: 0
Views: 1773
Reputation: 365707
If you want to make sure something is closed, you should close it, not just delete it and hope for the best.
First, del clip
doesn't actually delete the object; it just deletes the variable clip
. If clip
is the only reference to the object, then it becomes garbage. If you're using CPython, and if there are no circular references, the garbage will be detected immediately, and the object will be deleted. But if any of those three ifs are not true, it won't.
Second, even if you actually delete the object, that doesn't guarantee it will close things. Sure, that's how file objects work, and it's the way other objects that manage external resources should work, if there's no good reason to do otherwise, but it's not actually enforced by the language—sometimes there is a good reason, or sometimes, the 0.2 version of a library just hasn't gotten around to writing all the cleanup code.
In fact, from a quick look at the source, it looks like MoviePy has a good reason to not automatically close on deletion:
# Implementation note for subclasses:
#
# * Memory-based resources can be left to the garbage-collector.
# * However, any open files should be closed, and subprocesses should be terminated.
# * Be wary that shallow copies are frequently used. Closing a Clip may affect its copies.
# * Therefore, should NOT be called by __del__().
So, no, del clip
does not take care of closing for you.
And if you look at the examples in the docstrings for the module, like this one, they call close
explicitly:
>>> from moviepy.editor import VideoFileClip
>>> clip = VideoFileClip("myvideo.mp4").subclip(100,120)
>>> clip.write_videofile("my_new_video.mp4")
>>> clip.close()
So, you're presumably expected to do the same thing if you want things to be closed.
Upvotes: 2