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

ftputil操作FTP文件不支持a追加模式,如何保留旧内容写入新记录?

ftputil实现FTP文件末尾追加内容解决方案

ftputil 本身未实现 'a' 追加写入模式,直接使用 'a' 模式打开远程文件不会生效,使用 'w' 模式则会覆盖原有内容,可通过以下两种方案实现需求:


方案1:小文件通用方案(兼容性最优)

适用于文件体积不大,全量读取到内存不会产生过高开销的场景,无需依赖FTP服务端额外配置。
思路:先读取远程文件的原有内容,拼接新的待写入内容后,整体用 'w' 模式写回远程文件。

with ftputil.FTPHost(host, ftp_user, ftp_pass) as ftp_host:
    remote_file_path = "my_path_to_file_on_the_server"
    # 读取原有内容,文件不存在则旧内容为空
    old_content = ""
    if ftp_host.path.exists(remote_file_path):
        with ftp_host.open(remote_file_path, "r", encoding="utf-8") as fobj:
            old_content = fobj.read()
    
    # 生成待追加的新内容
    cupone_input = input('Enter coupons with a space: ')
    coupon_list = cupone_input.split(' ')
    new_content = ""
    for coupon in coupon_list:
        new_content += f'<p>Your coupon {coupon}</p>\n'
    
    # 拼接内容后写回远程文件
    full_content = old_content + new_content
    with ftp_host.open(remote_file_path, "w", encoding="utf-8") as fobj:
        write_length = fobj.write(full_content)
    
    print(f"追加完成,共写入{len(coupon_list)}条新记录,总写入字节:{write_length}")

方案2:大文件低内存方案

适用于远程文件体积较大,全量读取到内存会占用过高资源的场景。
思路:先将远程文件下载到本地临时文件,本地完成追加操作后,再上传覆盖远程文件。

import tempfile
import os

with ftputil.FTPHost(host, ftp_user, ftp_pass) as ftp_host:
    remote_file_path = "my_path_to_file_on_the_server"
    # 创建本地临时文件,关闭后不自动删除
    with tempfile.NamedTemporaryFile(mode='a+', encoding='utf-8', delete=False) as tmp_file:
        tmp_local_path = tmp_file.name
        # 若远程文件存在,先下载到临时文件
        if ftp_host.path.exists(remote_file_path):
            ftp_host.download(remote_file_path, tmp_local_path)
        # 追加新内容到临时文件
        coupon_list = input('Enter coupons with a space: ').split(' ')
        for coupon in coupon_list:
            tmp_file.write(f'<p>Your coupon {coupon}</p>\n')
    
    # 上传临时文件覆盖远程文件
    ftp_host.upload(tmp_local_path, remote_file_path)
    # 删除本地临时文件释放空间
    os.remove(tmp_local_path)

补充说明:如果你的FTP服务端支持REST(断点续传)指令,也可以直接定位到文件末尾写入新内容,不过该方法依赖服务端配置,兼容性不如上述两种通用方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:09:00