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

如何用Python批量为文件夹内txt文件末尾追加内容,with块应如何编写

是否需要使用pandas?

完全不需要。该需求仅为简单的文件末尾追加内容,Python原生文件IO即可实现,引入pandas反而会增加不必要的第三方依赖,处理大量小文件时的性能也远不如原生IO。

代码修改方案

你原有代码使用只读模式r打开文件,无法执行写入操作,直接改用追加模式a打开即可,不需要提前读取文件内容,修改后的完整代码如下:

import os

path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
    # a模式为追加模式,文件指针默认定位到文件末尾
    with open(os.path.join(path, file), 'a', encoding='utf-8') as f:
        # 写入换行符+end,保证end单独占一行,符合你的预期格式
        f.write('\nend')

如果需要避免部分文件末尾已有换行导致end前出现多余空行,可以调整为如下写法:

import os

path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
    file_path = os.path.join(path, file)
    # 先读取末尾字符判断是否需要补换行
    with open(file_path, 'rb') as f:
        f.seek(-1, os.SEEK_END)
        end_char = f.read()
    need_newline = end_char != b'\n'
    # 追加对应内容
    with open(file_path, 'a', encoding='utf-8') as f:
        f.write(f'\nend' if need_newline else 'end')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:42:00