将文件直接下载到 Python 中的文件系统
Download a file directly to filesystem in Python
有没有办法将文件直接流式传输到文件系统?即使连接丢失,我也想在 fs.conf 中查看该特定文件中的所有内容。就像 wget 或 curl。
但是,使用请求会导致首先下载响应内容然后将其写入文件系统的问题。
with open(file_name, "wb") as file:
response = get(url) # may take some time
file.write(response.content)
问题:虽然文件是 "downloading",但它存储在别处(我猜是在内存中或文件系统中的临时位置)。这意味着只要请求没有(成功)完成,我就有一个 0 字节的文件。
不使用第三方库能解决这个问题吗?
可以使用 requests
和 stream=true
实现直接流式传输到文件,或者参见 more useful examples
with open(file_name, 'wb') as f:
with requests.get(url, stream=True) as r:
shutil.copyfileobj(r.raw, f)
有没有办法将文件直接流式传输到文件系统?即使连接丢失,我也想在 fs.conf 中查看该特定文件中的所有内容。就像 wget 或 curl。
但是,使用请求会导致首先下载响应内容然后将其写入文件系统的问题。
with open(file_name, "wb") as file:
response = get(url) # may take some time
file.write(response.content)
问题:虽然文件是 "downloading",但它存储在别处(我猜是在内存中或文件系统中的临时位置)。这意味着只要请求没有(成功)完成,我就有一个 0 字节的文件。
不使用第三方库能解决这个问题吗?
可以使用 requests
和 stream=true
实现直接流式传输到文件,或者参见 more useful examples
with open(file_name, 'wb') as f:
with requests.get(url, stream=True) as r:
shutil.copyfileobj(r.raw, f)