在Python中处理CSV文件,你可以使用内置的`csv`模块。下面是一些基本的操作示例:
读取CSV文件
import csv
打开CSV文件
with open('example.csv', newline='', encoding='utf-8') as csvfile:
创建一个csv.reader对象
reader = csv.reader(csvfile)
遍历每一行
for row in reader:
print(row)
写入CSV文件
import csv
数据列表
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
打开文件以写入模式
with open('output.csv', 'w', newline='') as file:
创建一个csv.writer对象
writer = csv.writer(file)
写入数据
writer.writerows(data)
写入单行数据
import csv
数据列表
data = ['This', 'is', 'a', 'Test']
打开文件以写入模式
with open('example.csv', 'w', newline='') as file:
创建一个csv.writer对象
writer = csv.writer(file)
写入单行数据
writer.writerow(data)
使用`pandas`库
如果你需要更高级的功能,可以使用`pandas`库,它提供了更方便的`to_csv`方法。
import pandas as pd
数据字典
data_dict = {'Name': ['Tom', 'Lucy'], 'Age': [18, 20], 'Gender': ['male', 'female']}
创建DataFrame
df = pd.DataFrame(data_dict)
写入CSV文件
df.to_csv('data.csv', index=False)
以上示例展示了如何使用Python的`csv`模块进行基本的读写操作。