0

I would like to download a single file from a GitHub repository. In bash, you could do something like this:

curl -kLSs "https://github.com/mikolalysenko/lena/archive/master.tar.gz" | tar xz --wildcards '*lena.png' --strip-components=1`

to download and save this file in the current working directory. How would one do this using only Python (aka. not calling a bash command)?

Johannes Wiesner
  • 1,006
  • 12
  • 33

3 Answers3

2

Possible duplicate of How to download and write a file from Github using Requests

But if you want to avoid using external modules, the following code can work:

import urllib.request

url = ""
file_name = "file_name"

with urllib.request.urlopen(url) as file, open(file_name, 'w') as f:
    f.write(file.read().decode())

You can change open function parameters to save the file in your desired place

Pooia
  • 51
  • 5
1

I am not sure if with "pure python" you mean without modules, if not using the method urlretrive from the urllib module could be a solution:

import urllib.request


def main():
    urllib.request.urlretrieve("https://raw.githubusercontent.com/mikolalysenko/lena/master/lena.png", "test.png")


if __name__ == "__main__":
    main()

To download files from github you have to use the raw.githubusercontent.com domain, because the files of github repositories get stored there, but this answer explains it better.

Gabriel
  • 233
  • 1
  • 3
  • 11
0

I use this do download the zip embedded changlog.txt file from a project I follow on github.

import requests
from io import BytesIO
from pathlib import Path
from zipfile import ZipFile


file_name = 'lena.png'
timeout = 10
url = 'https://github.com/mikolalysenko/lena/archive/master.zip'

r = requests.get(url, timeout=timeout)
if r.ok:
    print('found:', Path(url).name)
    with ZipFile(BytesIO(r.content)) as f:
        for file in f.namelist():
            if file.endswith(file_name):
                print('found:', file)
                data = f.read(file)
                Path(Path(file).name).write_bytes(data)
else:
    print(r)
    print(r.text)
richard
  • 144
  • 3