You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将本地未解压的tar.gz文件上传至Azure Blob存储?

问题描述

我用Python从FTP服务器下载tar.gz文件时,误将文件解压后才保存到本地。现在想直接把未解压的原始tar.gz文件上传到Azure Blob存储,但尝试的上传代码无法成功,求排查问题。

原下载代码:

data = BytesIO()
save_file = ftp.retrbinary('RETR '+ filename, data.write, 1024)
data.seek(0)
uncompressed = gzip.decompress(data.read())
    
with open(filename, 'wb') as file:
    file.write(uncompressed)
    logging.info("success")

尝试的上传代码:

with open(filename, "rb") as f:
    blob.upload_blob(f, overwrite=True)
问题根源

你上传失败的核心原因是:本地保存的文件已经是解压后的内容,而非原始的tar.gz压缩包。原下载代码中执行了gzip.decompress(data.read()),把FTP获取的压缩包数据解压后才写入本地文件,导致上传时传递的不是目标tar.gz文件,自然无法得到预期结果。

修正方案

根据需求,有两种可行的修正方式:

方式1:修改下载代码,保存原始tar.gz文件后再上传

去掉解压步骤,直接把FTP获取的原始压缩数据写入本地文件:

data = BytesIO()
ftp.retrbinary('RETR '+ filename, data.write, 1024)
data.seek(0)

# 直接写入原始压缩数据,不做解压
with open(filename, 'wb') as file:
    file.write(data.read())
    logging.info("原始tar.gz文件保存成功")

# 再执行上传操作
with open(filename, "rb") as f:
    blob.upload_blob(f, overwrite=True)

方式2:跳过本地保存,直接从内存上传到Azure Blob

如果不需要本地留存文件,可以直接把内存中的原始压缩数据上传,提升效率:

data = BytesIO()
ftp.retrbinary('RETR '+ filename, data.write, 1024)
data.seek(0)  # 回到数据流起始位置

# 直接上传内存中的原始压缩数据,无需写入本地文件
blob.upload_blob(data, overwrite=True)

内容的提问来源于stack exchange,提问作者Kiran Qureshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:35:18