Skip to content

Instantly share code, notes, and snippets.

@jakelevi1996
Created January 31, 2020 09:40
Show Gist options
  • Select an option

  • Save jakelevi1996/c582f4b04bceef1bd3ccd16c5a0004da to your computer and use it in GitHub Desktop.

Select an option

Save jakelevi1996/c582f4b04bceef1bd3ccd16c5a0004da to your computer and use it in GitHub Desktop.
Downloading files in Python

Downloading files in Python

This is a simple script to check if a particular file exists in the same directory as the Python script; if the file doesn't exist, it is downloaded.

getpanda.py

import os, urllib.request

# Change to directory of current script (in case running from another location)
cd = os.path.dirname(__file__)
os.chdir(cd)

# Set filename and URL of panda
panda_fname = "panda.jpg"
panda_url = "https://upload.wikimedia.org/wikipedia/commons/f/fe/Giant_Panda_in_Beijing_Zoo_1.JPG"

# Check if file exists
if not os.path.isfile(panda_fname):
    # Download
    print("Panda file not present; downloading...")
    urllib.request.urlretrieve(panda_url, panda_fname)
    print("File downloaded successfully")
else:
    print("Panda file already present; not downloading")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment