Download and Save a file in python 2.7?

∥☆過路亽.° 提交于 2020-01-11 13:31:28

问题


Coming from here:

Basic http file downloading and saving to disk in python?

Is there any possibility to save the file in any folder? I tried this but i get error:

IOError: [Errno 2] No such file or directory:

import urllib

testfile=urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz","/myfolder/file.gz")

Any possibility to do it?


回答1:


You're most likely getting that error because /myfolder doesn't exist. Try creating it first

import os
import os.path
import urllib

destination = "/path/to/folder"
if os.path.exists(destination) is False:
    os.mkdirs(destination)
# You can also use the convenience method urlretrieve if you're using urllib anyway
urllib.urlretrieve("http://randomsite.com/file.gz", os.path.join(destination, "file.gz"))



回答2:


The directory /myfolder/file.gz doesn't available in your server or pc. Make a real file path which exists in your pc or server. For example:

./file.gz
file.gz

This will save the file from where you are running your script. In other words, in the same location to your python script.



来源:https://stackoverflow.com/questions/22440669/download-and-save-a-file-in-python-2-7

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