12

I'm trying to download youtube videos with pytube this way:

from pytube import YouTube
YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download()

but the file will have the same name as the original video name. How do I specify a custom filename?

klutt
  • 30,332
  • 17
  • 55
  • 95
ehsan shirzadi
  • 4,709
  • 16
  • 69
  • 112

4 Answers4

27

UPDATE:

The feature is now added. Do this:

YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
    .streams.first()
    .download(filename='filename')

Old answer:

This is not possible in the current latest (v7.0.18) release. The feature has been added, but no new release has been released since then. If you want to have this feature, you need to download the pytube repository: https://github.com/NFicano/pytube

If you have done so, you can use YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download(filename='filename')

It will automatically add the filename extension, so you don't have to include that.

I found it by reading the source. There, I found the declaration of the function download in the file streams.py:

def download(self, output_path=None, filename=None):

So you can obviously also specify a path.

For a good workaround, see landogardner's answer.

klutt
  • 30,332
  • 17
  • 55
  • 95
6

To add to klutt's answer, it doesn't look like there's been a new pypi release since this feature was added, so for now you can either download the code directly as klutt suggests, or, as a workaround, manually rename the file after the download() call, e.g.:

import os
from pytube import YouTube

yt = YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
yt.streams.first().download()
os.rename(yt.streams.first().default_filename, 'new_filename.ext')`
scrpy
  • 985
  • 6
  • 23
3

According to the Documentation, you can now specify a name for the stream you want to download by using the "filename" argument.

download(output_path=[path], filename=[name you want file to be saved as])
758Gianni
  • 73
  • 1
  • 2
  • 6
-1

from pytube import YouTube //any video link name = YouTube.YouTube('https://youtu.be/3ZAE7YU8dK8').title YouTube('http://youtube.com/watchv=9bZkp7q19f0').streams.first().download(filename = (f'{name}.mp4')

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – shamnad sherief Jan 25 '23 at 08:17