能否不创建磁盘临时文件直接下载文件内容?
直接下载文件内容到字节数组(无临时文件)
当然有办法,不用urllib.request.urlretrieve,改用urllib.request.urlopen就能直接把文件内容读到内存中的字节数组,全程不会生成磁盘临时文件。
基础实现(一次性读取)
import urllib.request target_url = "你的目标文件URL" with urllib.request.urlopen(target_url) as response: # 读取全部内容,返回bytes类型(即字节数组) byte_content = response.read() # 验证类型 print(type(byte_content)) # 输出: <class 'bytes'>
大文件分块读取(避免内存过载)
如果要处理大文件,怕一次性加载占内存过高,可以分块读取并拼接:
import urllib.request target_url = "你的目标文件URL" chunk_size = 1024 * 1024 # 每次读取1MB byte_content = b'' with urllib.request.urlopen(target_url) as response: while chunk := response.read(chunk_size): byte_content += chunk
urlopen返回的响应对象支持流式读取,read()方法直接将远程内容加载到内存,完全绕开了临时文件的生成,正好满足你的需求。
内容的提问来源于stack exchange,提问作者matthias_buehlmann
相关产品推荐
相关产品推荐

