# 打开 testfile1.txt 和 testfile2.txt 文件,并读取内容 with open('testfile1.txt', 'r') as f1, open('testfile2.txt', 'r') as f2: content1 = f1.read() content2 = f2.read() # 合并两个文件的内容 merged_content = content1 + content2 # 将合并后的内容写入 testfile3.txt 文件中 with open('testfile3.txt', 'w') as f3: f3.write(merged_content) # 输出合并后的内容到屏幕 print(merged_content)如果testfile1.txt 和 testfile2.txt两个文件不存在就先往里面写入创建然后,顺序为:testfile1.txt在前,testfile2.txt在后
时间: 2023-07-16 19:11:41 浏览: 85
好的,可以使用以下代码来实现:
```python
# 先创建 testfile1.txt 和 testfile2.txt 文件
with open('testfile1.txt', 'w') as f1, open('testfile2.txt', 'w') as f2:
f1.write('Hello')
f2.write('World')
# 打开 testfile1.txt 和 testfile2.txt 文件,并读取内容
with open('testfile1.txt', 'r') as f1, open('testfile2.txt', 'r') as f2:
content1 = f1.read()
content2 = f2.read()
# 合并两个文件的内容
merged_content = content1 + content2
# 将合并后的内容写入 testfile3.txt 文件中
with open('testfile3.txt', 'w') as f3:
f3.write(merged_content)
# 输出合并后的内容到屏幕
print(merged_content)
```
这段代码会先创建 testfile1.txt 和 testfile2.txt 文件,并分别往里面写入 'Hello' 和 'World'。然后打开这两个文件,并读取内容,将它们合并成一个字符串。最后将合并后的内容写入 testfile3.txt 文件中,并输出到屏幕上。如果 testfile1.txt 和 testfile2.txt 文件不存在,这段代码会自动创建它们。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)