Skip to content

Instantly share code, notes, and snippets.

@paultopia
Created April 5, 2018 02:46
Show Gist options
  • Select an option

  • Save paultopia/f872dc8caa8a308ee828470b192d9719 to your computer and use it in GitHub Desktop.

Select an option

Save paultopia/f872dc8caa8a308ee828470b192d9719 to your computer and use it in GitHub Desktop.
readzip.py
# quick and dirty script to download a compressed file and unzip it in memory to an appropriate folder
# useful in pythonista (ios) to handle the fact that ios has no native way to handle compressed files.
# can handle .tar.gzip and .zip files
import requests, zipfile, os, urllib, io, tarfile
url = input('url: ')
filename = os.path.basename(urllib.parse.urlparse(url).path)
dirname = filename.partition(".")[0]
extension = filename.rpartition(".")[-1]
try:
os.makedirs(dirname)
except OSError as e:
print('directory creation failed')
raise
response = requests.get(url)
if filename.endswith('.tar.gz') or filename.endswith(".tgz"):
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tarred:
tarred.extractall(dirname)
print('file unzipped in '+ dirname)
elif filename.endswith("tar"):
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:") as tarred:
tarred.extractall(dirname)
print('file unzipped in '+ dirname)
elif filename.endswith('.zip'):
with zipfile.ZipFile(io.BytesIO(response.content)) as zipped:
zipped.extractall(dirname)
print('file unzipped in '+ dirname)
else:
print("can't recognize compressed file type'")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment