Download an internet resource in Python and save it on my desired location

只愿长相守 提交于 2019-12-08 05:59:32

问题


I am new to Python and I am using urllib2 to download files over the internet. I am using this code

import urllib2
response = urllib2.urlopen('http://www.example.com/myfile.zip')
...

This code actually save the zip file on my temp folder, I don't want it to be like that, I want to save it on my desired location. Is it possible?


回答1:


You can use the urllib.urlretrieve function, to download the distant file to your local filesystem.

>>> import urllib
>>> urllib.urlretrieve('http://www.example.com/myfile.zip', 'path/to/download/dir/myfile.zip')

See the urllib.urlretrieve documentation for more info.




回答2:


Simply use something like this :

f = open("path_to_your_file_to_save", 'w')
f.write(urllib.urlopen(url).read())
f.close()

Where path_to_your_file_to_save equals [path_where_save] + [filename.ext]



来源:https://stackoverflow.com/questions/16479365/download-an-internet-resource-in-python-and-save-it-on-my-desired-location

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!