Redirecting downloaded file to users downloads folder (Python)

Viewed 583

I was attempting to build a simple youtube video downloader app using python and tkinter as excercise. I did end up successfully making an app to download videos yet I wish to be able to redirect to users download folder so it does not download it next to the executable. The following is how I download the videos using pytube:

from pytube import YouTube
video = YouTube("https://www.youtube.com/watch?v=Wcj_tkFAX-o").streams.get_highest_resolution().download()
1 Answers

You want to pass the file path to the download() function call at the end. A cross platform way to do this is:

from pytube import YouTube
import os

if os.name == "nt":
    DOWNLOAD_FOLDER = f"{os.getenv('USERPROFILE')}\\Downloads"
else:  # PORT: For *Nix systems
    DOWNLOAD_FOLDER = f"{os.getenv('HOME')}/Downloads"

video = YouTube("https://www.youtube.com/watch?v=Wcj_tkFAX-o").streams.get_highest_resolution().download(DOWNLOAD_FOLDER)

Explanation

the calls to os.getenv get the environment variable for the path to the user. For example if you have a windows account with the name "kieran" on the C drive then os.getenv('USERPROFILE') == "C:\\Users\\Kieran". Which you can then add the Downloads to at the end. This also works in your file explorer, and CMD you can go into the top of file explorer and type %USERPROFILE% and it will take you to that folder, or type it into CMD to see the result.

On linux/MacOS it's the same principle except the variable is called HOME.

Additional details

Just keep in mind that these folders may not always exist for all user types, some installs of linux in particular exclude the Downloads folder. Likewise some windows server installs don't have the folder either.

Extra tips for pytube

I also just wanted to give you this heads up since I just wrote a wrapper for pytube recently you should also do some error checking because pytube can throw a lot of errors if the video is unavailable for any reason. You can see this code for an example of the various potential situations and exceptions I encountered while working with the library.

Related