Search code examples
python-3.xiopython-requests

Python adding files from URL to file on local file


I am trying to combine two files from the internet, and save the output on my computer. I have the below code,but no made what I try I always get the same result. I get the first URL, and nothing more. To be exact, I am trying to comebine VideoURL and videoURL1, together into one file called output.mp4...

videoURL= 'http://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'
videoURL1 = 'http://techslides.com/demos/sample-videos/small.mp4'
# print(str(embeddHTMLString).find('sources: ['))

local_filename = videoURL.split('/')[-1]
# NOTE the stream=True parameter

response = urlopen(videoURL)

response1 = urlopen(videoURL1)

with open(local_filename, 'wb') as f:
    while True:
        chunk = response.read(1024)
        if not chunk:
            break
        f.write(chunk)
with open(local_filename, 'ab+') as d:
    while True:
        chunk1 = response1.read(1024)
        if not chunk1:
            break
        d.write(chunk1)

Solution

  • You're doing it wrong. The gist of this answer has already been given by @Tempo810, you need to download the files separately and concatenate them into a single file later.

    I am assuming you have both video1.mp4 and video2.mp4 downloaded from your urls separately. Now to combine them, you simply cannot use append to concat the files, since video files contains format header and metadata, and combining two media files into one means you need to rewrite new metadata and format header, and remove the old ones.

    Instead you can use the the library moviepy to save yourself. Here is a small sample of code how to utilise moviepy's concatenate_videoclips() to concat the files:

    from moviepy.editor import VideoFileClip, concatenate_videoclips
    # opening the clips
    clip1 = VideoFileClip("video1.mp4")
    clip3 = VideoFileClip("video2.mp4")
    # lets concat them up
    final_clip = concatenate_videoclips([clip1,clip2])
    final_clip.write_videofile("output.mp4")
    

    Your resulting combined file is output.mp4. Thats it!