python实现将多个文件内容合并到一个文件
时间: 2023-11-27 11:03:56 浏览: 465
可以使用Python中的文件操作来实现将多个文件内容合并到一个文件。具体实现步骤如下:
1. 打开要合并的多个文件(假设文件名为file1.txt、file2.txt、file3.txt等)和要合并到的文件(假设文件名为merged_file.txt)。
```python
file_list = ["file1.txt", "file2.txt", "file3.txt"]
merged_file = open("merged_file.txt", "w")
```
2. 循环遍历所有要合并的文件,将每个文件的内容逐行写入到合并文件中。
```python
for file_name in file_list:
with open(file_name, "r") as f:
merged_file.write(f.read())
```
3. 关闭所有文件。
```python
merged_file.close()
```
完整代码如下:
```python
file_list = ["file1.txt", "file2.txt", "file3.txt"]
merged_file = open("merged_file.txt", "w")
for file_name in file_list:
with open(file_name, "r") as f:
merged_file.write(f.read())
merged_file.close()
```
阅读全文
相关推荐














