I'm trying to write a basic python script that downloads videos from youtube, clips 10 seconds of it, and then concats it with another pre-downloaded video I have in my root directorywhatever.mp4
.
I have a list of search words in words.txt
that I loop over and download when I run my python script:
import urllib.request
import re
from pytube import YouTube
import os
from moviepy.editor import VideoFileClip, concatenate_videoclips
f = open('words.txt', 'r')
for line in f:
y = line.split()
link = urllib.request.urlopen(f"https://www.youtube.com/results?search_query={y}")
pattern = r"watch\?v=(\S{11})"
video_ids = re.findall(pattern, link.read().decode())
vid = f"https://www.youtube.com/watch?v={video_ids[0]}"
yt = YouTube(vid)
yt.streams.filter(mime_type="video/mp4", progressive=True).first().download(output_path='highlights', filename=f"{y}.mp4")
print("Video downloaded as mp4")
for filename in os.listdir("videos"):
clip = VideoFileClip(filename).subclip(0, 10)
rick = VideoFileClip('whatever.mp4')
new = concatenate_videoclips([clip, whatever])
new.write_videofile(f'new_{filename}.mp4')
f.close()
When I run the script the first video downloads successfully, but I get this error:
$ python3 index.py
Traceback (most recent call last):
File "/Users/me/Desktop/Code/pytube_moviepy/index.py", line 23, in <module>
clip = VideoFileClip(str(filename)).subclip(0, 10)
File "/opt/homebrew/lib/python3.9/site-packages/moviepy/video/io/VideoFileClip.py", line 88, in __init__
self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt,
File "/opt/homebrew/lib/python3.9/site-packages/moviepy/video/io/ffmpeg_reader.py", line 35, in __init__
infos = ffmpeg_parse_infos(filename, print_infos, check_duration,
File "/opt/homebrew/lib/python3.9/site-packages/moviepy/video/io/ffmpeg_reader.py", line 270, in ffmpeg_parse_infos
raise IOError(("MoviePy error: the file %s could not be found!\n"
OSError: MoviePy error: the file video1.mp4 could not be found!
Please check that you entered the correct path.
Everything else seems to be working which is why I'm confused:
- The video is downloaded.
- The video is saved as
video1.mp4
in thevideos
directory. - MoviePy can't find the file.
What's more confusing is that if my whatever.mp4
file into the videos
directory and then run the second half of my script (by commenting out the first for loop) the videos get concatenated. What am I doing wrong? What's the issue?
My file layout:
.
├── Pipfile
├── Pipfile.lock
├── videos
│ └── video1.mp4
├── index.py
├── words.txt
└── whataver.mp4