Ajay Tatachar
Ajay Tatachar

Reputation: 383

How do I download a tarball with python?

I'm trying to download a tarball by downloading the contents and then writing them to a file. This is basically how my code works:

from urllib import urlretrieve

contents = urlretrieve('http://example.com/file.tgz')
open('/tmp/my-tar.tgz', 'w').write(contents)

However, when I do that, I get an error (a TypeError) that says 'expected a character buffer object' in the call to write.

How would I write the contents of a tarball to a file?

Upvotes: 3

Views: 2794

Answers (1)

Nick ODell
Nick ODell

Reputation: 25210

From the docs:

urllib.urlretrieve(url[, filename[, reporthook[, data]]])

Copy a network object denoted by a URL to a local file, if necessary. If the URL points to a local file, or a valid cached copy of the object exists, the object is not copied. Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object, possibly cached). Exceptions are the same as for urlopen().

write is complaining because it expects to get the contents of what you're trying to write, but it's actually getting a (filename, headers) tuple.

Fixed version:

from urllib import urlretrieve

filename, headers = urlretrieve('http://example.com/file.tgz', '/tmp/my-tar.tgz')

Upvotes: 4

Related Questions