Skip to main content
 首页 » 编程设计

python之如何在不将整个文件读入内存的情况下在 python 3 中从 Internet 写入大型二进制文件

2025年05月04日14dyllove98

This answer提供了一种使用 Python 3 从 Internet 下载文件的非常有用的方法。

基本上它说要使用:

with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file: 
    shutil.copyfileobj(response, out_file) 

如果url指定了一个大文件,response不是自动存入内存了吗? IE。即使 copyfileobj 缓冲了文件,难道不只是让请求返回整个大文件作为 response 吗?

请您参考如下方法:

不,urlopen 将通过套接字返回类似对象的文件。引用:

Open a network object denoted by a URL for reading. If the URL does not have a scheme identifier, or if it has file: as its scheme identifier, this opens a local file (without universal newlines); otherwise it opens a socket to a server somewhere on the network. If the connection cannot be made the IOError exception is raised. If all went well, a file-like object is returned. This supports the following methods: read(), readline(), readlines(), fileno(), close(), info(), getcode() and geturl().

因为 seek 方法既不被 urlopen 支持,也不被 copyfileobj 使用,我们可以推断没有必要将所有内容存储在内存中。