python 合并文件
时间: 2023-09-07 22:17:54 浏览: 51
有多种方法可以合并文件,以下是其中两种方法:
方法一:使用Python内置的文件操作函数
```python
# 打开要合并的文件
file1 = open("file1.txt", "r")
file2 = open("file2.txt", "r")
# 读取文件内容并合并
content1 = file1.read()
content2 = file2.read()
merged_content = content1 + content2
# 创建新文件并写入合并后的内容
merged_file = open("merged_file.txt", "w")
merged_file.write(merged_content)
# 关闭文件
file1.close()
file2.close()
merged_file.close()
```
方法二:使用Python的文件操作库Pandas
```python
import pandas as pd
# 读取要合并的文件
file1 = pd.read_csv("file1.csv")
file2 = pd.read_csv("file2.csv")
# 合并文件
merged_file = pd.concat([file1, file2])
# 将合并后的文件写入新文件
merged_file.to_csv("merged_file.csv", index=False)
```
其中,`pd.read_csv()`和`pd.concat()`是Pandas库提供的函数,可以读取和合并CSV文件。`to_csv()`函数可以将数据写入CSV文件。