在Python中,合并CSV文件可以通过多种方式实现,以下是几种常见的方法:
方法一:使用csv模块
```python
import csv
import glob
获取所有CSV文件的路径
file_paths = glob.glob('path/to/csv/files/*.csv')
merged_data = {}
逐个读取每个CSV文件,并将其添加到字典中
for file_path in file_paths:
with open(file_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
假设每个文件都有一个唯一的标识符,例如文件名
identifier = os.path.basename(file_path)
merged_data[identifier] = row
将字典写入新的CSV文件
with open('merged.csv', 'w', newline='') as outfile:
fieldnames = merged_data[next(iter(merged_data))].keys()
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
for identifier, row in merged_data.items():
writer.writerow(row)
方法二:使用pandas库
```python
import pandas as pd
import glob
获取所有CSV文件的路径
file_paths = glob.glob('path/to/csv/files/*.csv')
创建一个空的DataFrame,用于存储合并后的数据
df = pd.DataFrame()
逐个读取每个CSV文件,并将其添加到DataFrame中
for file_path in file_paths:
temp_df = pd.read_csv(file_path, encoding='gbk') 根据需要设置编码格式
file_name = os.path.basename(file_path)
temp_df['file_name'] = file_name 添加文件名作为新的一列
df = df.append(temp_df, ignore_index=True)
将合并后的DataFrame保存为新的CSV文件
df.to_csv('merged.csv', index=False)
方法三:使用csv模块以追加模式合并
```python
import csv
import glob
获取所有CSV文件的路径
file_paths = glob.glob('path/to/csv/files/*.csv')
以追加模式打开源文件
with open('source.csv', 'a', newline='') as csv_file:
创建csv的写对象,并传入表头
writer = csv.DictWriter(csv_file, fieldnames=header)
批量写入读取到的数据
for row in reader:
writer.writerow(row)
以上方法展示了如何使用Python的csv模块和pandas库来合并CSV文件。请根据你的具体需求选择合适的方法。