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

如何用Python读取多个文本/CSV文件并生成指定格式的输出文件

Python脚本实现方案

核心逻辑

  • 逐行读取文件A、B的内容,去除每行末尾的换行符/空白字符
  • 使用zip()函数将两个文件的行按顺序一一配对(行数不一致时自动以较短的文件为准)
  • 按要求格式化生成Insert和Update语句,写入输出文件

完整代码(无需额外文件C)

# 读取两个输入文件的内容,逐行处理去除换行符
with open('a.txt', 'r', encoding='utf-8') as fa:
    nums_a = [line.strip() for line in fa if line.strip()]
with open('b.txt', 'r', encoding='utf-8') as fb:
    nums_b = [line.strip() for line in fb if line.strip()]

# 打开输出文件写入内容
with open('output.txt', 'w', encoding='utf-8') as f_out:
    # 逐对拼接生成SQL
    for num1, num2 in zip(nums_a, nums_b):
        # 按要求拼接内容,每对之间空一行分隔
        content = f"""Insert into Table A
Where Num1 = {num1}
and Num2 = {num2}
Update Table A
Where Num1 = {num1}
and Num2 = {num2}

"""
        f_out.write(content)

使用文件C存储静态模板的实现方式

  1. 先在文件c.txt中写入带占位符的模板内容:
Insert into Table A
Where Num1 = {num1}
and Num2 = {num2}
Update Table A
Where Num1 = {num1}
and Num2 = {num2}

  1. 对应调整代码:
# 读取模板内容
with open('c.txt', 'r', encoding='utf-8') as fc:
    template = fc.read()

with open('a.txt', 'r', encoding='utf-8') as fa:
    nums_a = [line.strip() for line in fa if line.strip()]
with open('b.txt', 'r', encoding='utf-8') as fb:
    nums_b = [line.strip() for line in fb if line.strip()]

with open('output.txt', 'w', encoding='utf-8') as f_out:
    for num1, num2 in zip(nums_a, nums_b):
        f_out.write(template.format(num1=num1, num2=num2))

注意事项

  • 代码中if line.strip()的作用是自动跳过两个输入文件里的空行,不需要可以直接删除
  • 如果两个文件行数不一致,默认输出到较短文件的最大行数为止,如果需要对缺失行补默认值,可以自行补充判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:45:04