在 python 2.7 中下载并保存文件?

2024-01-01

从这里出发:

在Python中基本的http文件下载并保存到磁盘? https://stackoverflow.com/questions/19602931/basic-http-file-downloading-and-saving-to-disk-in-python?lq=1

是否可以将文件保存在任何文件夹中?我尝试了这个,但出现错误:

IOError: [Errno 2] 没有这样的文件或目录:

import urllib

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

有可能做到吗?


您很可能会收到该错误,因为 /myfolder 不存在。首先尝试创建它

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"))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python 2.7 中下载并保存文件? 的相关文章

随机推荐