Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

urllib.request for python 3.3 not working to download file

I would like to download a large archive file with python and save it, but urllib is not working for me. This is my code:

    import urllib
    urllib.request("http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt")

Note that the link I used in this example is not a large archive. I am only using it as an example. It links directly to a .txt file, so it should work. I am getting this error:

    Traceback (most recent call last):
    File "<pyshell#11>", line 1, in <module>
    urllib.request("http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt")
    AttributeError: 'module' object has no attribute 'request'

It seems to me like urllib is somehow broken and missing the "request" method. I am using Python 3.3. Should I be using another module or is it actually a Python problem?

like image 303
user2218101 Avatar asked Jun 07 '26 23:06

user2218101


2 Answers

No, it is not broken. The urllib.request documentation is pretty clear on how this works:

import urllib.request
req = urllib.request.urlopen('http://www.google.com')
data = req.read()

Edit: If you need to write the file directly to disk rather than process the data, use urlretrieve.

urllib.request.urlretrieve('http://example.com/big.zip', 'file/on/disk.zip')
like image 66
ChrisP Avatar answered Jun 10 '26 14:06

ChrisP


To download an url into a file, you could use urlretrieve() function:

from urllib.request import urlretrieve
url = "http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt"
urlretrieve(url, "result.txt")
like image 40
jfs Avatar answered Jun 10 '26 14:06

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!