简体   繁体   English

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

[英]Download and Save a file in python 2.7?

Coming from here: 来自这里:

Basic http file downloading and saving to disk in python? 基本的HTTP文件下载并保存到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: IOError:[Errno 2]没有这样的文件或目录:

import urllib

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

Any possibility to do it? 有可能吗?

You're most likely getting that error because /myfolder doesn't exist. 您最有可能收到该错误,因为/ myfolder不存在。 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"))

The directory /myfolder/file.gz doesn't available in your server or pc. 目录/myfolder/file.gz在您的服务器或PC中不可用。 Make a real file path which exists in your pc or server. 制作一个存在于您的PC或服务器中的真实文件路径。 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. 换句话说,在与python脚本相同的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM