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

Python FTP_TLS下载tar.gz文件无法用7-Zip打开问题求助

问题成因

该问题和retrbinary的blocksize参数无关,核心是代码逻辑错误导致下载的tar.gz文件被损坏:

  • 下载tar.gz压缩包时,你用localfile变量存储压缩包的本地保存路径,二进制写入完成后,又以文本覆盖写入模式'w'重新打开了同一个localfile路径,将对应md5校验文件的内容直接写入了压缩包文件中。原本的二进制压缩包数据被完全替换为md5文本内容,自然无法被7-Zip识别为有效归档。
  • 额外隐患:Windows平台下文本模式写入文件会自动将换行符\n转换为\r\n,即使路径配置正确,直接用retrlines写入文本文件也可能出现内容与源文件不一致的问题。
修复方案
  • 为md5校验文件单独配置本地存储路径,绝对不能和tar.gz压缩包共用同一路径,避免覆盖已下载的压缩包数据。
  • 小文件下载优先统一用retrbinary二进制模式传输,规避不同平台文本模式的换行转换问题,也不需要手动处理换行符拼接。
  • 下载完成后可增加md5校验逻辑,确认文件完整性。
修正后的核心代码片段
def get_ftp(ip, login, passwd, path):
    """ Connexion FTP """
    try:
        with ftplib.FTP_TLS(ip, login, passwd) as ftps:
            ftps.prot_p()
            files = ftps.nlst('/home/user/dir/' + path)

            if files:
                for file in files:
                    if file.endswith('.tar.gz'):
                        md5_remote_path = f"{file}.md5"
                        if md5_remote_path in files:
                            localfile = join(path_recu, basename(file))
                            # 下载tar.gz压缩包
                            with open(localfile, 'wb') as binary_file:
                                response = ftps.retrbinary('RETR %s' % file, binary_file.write, blocksize=8192, rest=None)
                            if response.startswith('226'):
                                # 单独设置md5文件存储路径,二进制模式写入
                                md5_localfile = localfile + '.md5'
                                with open(md5_localfile, 'wb') as md5_file:
                                    ftps.retrbinary('RETR %s' % md5_remote_path, md5_file.write)

    except ftplib.error_perm as resp:
        if str(resp):
            logger.critical('ERREUR : ' + repr(resp))
            raise
    else:
        return files

修复后重新下载的tar.gz文件即可正常被7-Zip打开解压。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:06:23