如何用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存储静态模板的实现方式
- 先在文件
c.txt中写入带占位符的模板内容:
Insert into Table A Where Num1 = {num1} and Num2 = {num2} Update Table A Where Num1 = {num1} and Num2 = {num2}
- 对应调整代码:
# 读取模板内容 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
相关产品推荐
相关产品推荐

