假设有两个文本文件 file1txt 和 file2txt编写程序 mergepy把两个文本文件中的内容合并到新文件 resulttxt 中要求文件 file1txt 和 file2txt 中的行在 resulttxt 中交替出现。也就是说resulttxt 文件中的奇数行来自 file1txt而偶数行来自 file2txt。如果两个文件行数不一样那么处理完行数较少的文件之后把另一个文件中剩余的所
以下是一个实现上述要求的 merge.py 程序的示例代码:
def merge(file1, file2, result):
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(result, 'w') as res:
lines1 = f1.readlines()
lines2 = f2.readlines()
min_lines = min(len(lines1), len(lines2))
for i in range(min_lines):
res.write(lines1[i])
res.write(lines2[i])
if len(lines1) > len(lines2):
for i in range(min_lines, len(lines1)):
res.write(lines1[i])
elif len(lines2) > len(lines1):
for i in range(min_lines, len(lines2)):
res.write(lines2[i])
# 测试
merge('file1.txt', 'file2.txt', 'result.txt')
注意:上述代码假设 file1.txt 和 file2.txt 文件已经存在,并且程序会将结果写入 result.txt 文件中。如果 result.txt 文件已经存在,那么运行程序会覆盖该文件中的内容。如果需要追加到 result.txt 文件的末尾,可以将 open(result, 'w') 改为 open(result, 'a')
AI 优化版
原文地址:https://www.cveoy.top/t/topic/hDZw 著作权归作者所有。请勿转载和采集!