编写一个程序,将两个不同文本文件中对应行上的内容合并(拼接)后输出到 第三个文件
时间: 2024-04-12 17:27:20 浏览: 10
您好!您可以使用以下的 Python 代码来实现文本文件内容的合并:
```python
def merge_files(file1, file2, output_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output_file, 'w') as output:
lines1 = f1.readlines()
lines2 = f2.readlines()
# 确保两个文件行数相同
if len(lines1) != len(lines2):
print("两个文件行数不一致!")
return
# 逐行合并并写入第三个文件
for line1, line2 in zip(lines1, lines2):
merged_line = line1.strip() + line2.strip() + '\n'
output.write(merged_line)
print("合并完成!")
# 使用示例
merge_files('file1.txt', 'file2.txt', 'output.txt')
```
请确保将 'file1.txt'、'file2.txt' 替换为您实际的文件名,'output.txt' 替换为您想要输出的合并文件名。该代码会读取两个文件的内容,逐行合并后写入第三个文件中。如果两个文件的行数不相同,则会打印出错误信息。
希望这能帮到您!如果您有任何进一步的问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)