python有两个文件file1.txt和file2.txt,将内容合并写入到文件file3.txt中
时间: 2024-03-09 11:49:17 浏览: 349
可以使用以下Python代码将 `file1.txt` 和 `file2.txt` 的内容合并写入到新文件 `file3.txt` 中:
```python
with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2, open('file3.txt', 'w') as f3:
f3.write(f1.read())
f3.write(f2.read())
```
这段代码中,我们使用 `with` 语句打开三个文件,然后使用 `write()` 方法将 `file1.txt` 和 `file2.txt` 的内容写入到 `file3.txt` 中。最后,`with` 语句自动关闭了所有打开的文件。
需要注意的是,以上代码将两个文件的内容简单地合并在一起,没有做任何去重或排序操作。如果需要按照一定规则合并文件内容,还需要根据具体需求进行修改。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)