The COCO train2017 images come as one zip: 18.01 GB and 118,287 photos. I wanted one photo. The usual way is to download all 18 GB, unzip, and delete almost everything.

This script got that photo in 6 HTTP requests and 12.9 MB:

$ python remote_zip.py http://images.cocodataset.org/zips/train2017.zip train2017/000000147328.jpg 118,288 files, 18.01 GB zip Files saved: 1 6 requests, 12.9 MB downloaded 

It uses only Python's standard library. Below is how it works and the full code.

Why a zip can be read in parts

A zip file is a row of compressed files, with a list of all of them at the very end. That list is called the central directory. For every file it stores the name, the sizes, a CRC-32 checksum, and the byte offset where that file starts.

So to get one file you need two pieces of the zip:

  1. The central directory at the end, to find where your file is.
  2. The bytes of that one file.

Everything else can stay on the server.

Asking a server for part of a file

HTTP has a header for this. You send Range: bytes=1000-1999 and a server that supports it answers 206 Partial Content with just those 1,000 bytes. Most static file hosts support it: S3, Google Cloud Storage, Hugging Face, most CDNs and plain nginx or Apache. Download managers use it to resume.

You can try it with curl:

curl -s -r 0-0 -D - -o /dev/null http://images.cocodataset.org/zips/train2017.zip 
HTTP/1.1 206 Partial Content Content-Range: bytes 0-0/19336861798 

The number after the slash is the size of the whole file.

The trick: give zipfile a file that lives on a server

Python's zipfile already knows how to find the central directory, read it, and decompress one file. It only needs a file object it can seek() and read(). So the whole job is to write a file object where every read becomes a Range request.

import io import sys import urllib.request import zipfile class HttpFile(io.RawIOBase): """A file on a web server that zipfile can seek around in, one Range request per read.""" def __init__(self, url): # Ask for the first byte. HEAD would be simpler, but some servers (Kaggle) answer it with 404. req = urllib.request.Request(url, headers={"Range": "bytes=0-0"}) with urllib.request.urlopen(req) as r: if r.status != 206: sys.exit("This server can't send part of a file.") self.url = r.url # after redirects, so later requests skip them self.size = int(r.headers["Content-Range"].split("/")[1]) self.pos = self.requests = self.downloaded = 0 def seekable(self): return True def readable(self): return True def tell(self): return self.pos def seek(self, offset, whence=io.SEEK_SET): base = {io.SEEK_SET: 0, io.SEEK_CUR: self.pos, io.SEEK_END: self.size}[whence] self.pos = base + offset return self.pos def readinto(self, buf): end = min(self.pos + len(buf), self.size) - 1 if end < self.pos: return 0 req = urllib.request.Request(self.url, headers={"Range": f"bytes={self.pos}-{end}"}) with urllib.request.urlopen(req) as r: data = r.read() buf[: len(data)] = data self.pos += len(data) self.requests += 1 self.downloaded += len(data) return len(data) url = sys.argv[1] raw = HttpFile(url) z = zipfile.ZipFile(io.BufferedReader(raw, buffer_size=1 << 20)) names = z.namelist() print(f"{len(names):,} files, {raw.size / 2**30:.2f} GB zip") if len(sys.argv) > 2: # A file name, or a folder like "train2017/" to take everything in it picked = [n for n in names if n.startswith(sys.argv[2]) and not n.endswith("/")] for name in picked: z.extract(name) print(f"Files saved: {len(picked):,}") else: for name in names[:10]: print(" ", name) print(f"{raw.requests} requests, {raw.downloaded / 2**20:.1f} MB downloaded") 

seek() only moves a number. No bytes are fetched until zipfile reads, so jumping to the end of an 18 GB file is free.

readinto() turns each read into one Range request for exactly the bytes asked for.

io.BufferedReader(raw, buffer_size=1 << 20) matters more than it looks. zipfile reads in small pieces, often a few dozen bytes at a time. Without a buffer, that's one HTTP request per piece and the script crawls. With a 1 MB buffer, small reads are served from memory and the server sees a few big requests.

The first request asks for one byte with a normal GET. I started with a HEAD request, which is the textbook way to get a file's size, and Kaggle answered it with 404. A ranged GET works there too, and r.url keeps the address after redirects so later requests go straight to the storage server.

Running it

List what's inside without downloading the zip:

python remote_zip.py http://images.cocodataset.org/zips/train2017.zip 

Take one file:

python remote_zip.py http://images.cocodataset.org/zips/train2017.zip train2017/000000147328.jpg 

Take a whole folder by giving its name with a slash at the end:

python remote_zip.py https://www.kaggle.com/api/v1/datasets/download/paultimothymooney/chest-xray-pneumonia chest_xray/test/ 

That last one took the 624 test images out of a 2.29 GB Kaggle dataset in 79 requests and 77.2 MB.

Where the 12.9 MB went

For the COCO photo, 12.9 MB were downloaded and the photo itself is 284 KB. Almost everything else is the central directory: 118,288 names and offsets take about 12 MB. That's a fixed cost. Once the list is read you can take one photo or a thousand, and each one costs about its own size.

zipfile also checks each file's CRC-32 as it decompresses, so a damaged download raises an error instead of quietly giving you a broken file.

When it doesn't work

  • The server doesn't support Range. GitHub's green "Download ZIP" button is the common one: GitHub builds that zip while it sends it, so there's nothing to seek in. The script stops with a message. The only option there is to read the zip from start to end.
  • ZIP64. Zips over 4 GB or with more than 65,535 files use 64-bit fields. Python's zipfile handles them, which is why COCO works.
  • Speed. The script fetches one piece at a time. For many small files that's slow: the 624 Kaggle images took about a minute and a half. Running several requests in parallel is the obvious next step.

If you need this in a project, the remotezip library on PyPI does the same thing with more options.

Without code

I built LinkUnzip around this idea. It's a free, open-source browser extension for Chrome, Edge and Brave: you paste a zip's link, see every file with its size, tick what you want, and only those files are downloaded, several at a time. It can also give you a Python command for the files you ticked, to run on a server. Here's the COCO example measured step by step.

In the next post: the servers that broke all of this in ways my tests never did.