python读取两个文件合并
时间: 2023-07-18 13:06:53 浏览: 32
可以使用Python中的文件操作来读取两个文件并合并它们。具体操作如下:
1. 打开第一个文件并读取内容:
```python
with open('file1.txt', 'r') as f1:
content1 = f1.read()
```
2. 打开第二个文件并读取内容:
```python
with open('file2.txt', 'r') as f2:
content2 = f2.read()
```
3. 将两个文件的内容合并:
```python
merged_content = content1 + "\n" + content2
```
4. 将合并后的内容写入新文件:
```python
with open('merged_file.txt', 'w') as f:
f.write(merged_content)
```
完整代码如下:
```python
with open('file1.txt', 'r') as f1:
content1 = f1.read()
with open('file2.txt', 'r') as f2:
content2 = f2.read()
merged_content = content1 + "\n" + content2
with open('merged_file.txt', 'w') as f:
f.write(merged_content)
```
注意:如果文件内容较大,一次读取可能会导致内存溢出,可以使用逐行读取的方式来避免。
相关推荐
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)