使用Python处理CSV数据可以通过使用csv模块来读取、写入和操作CSV文件。以下是一些常用的处理CSV数据的方法:
读取CSV文件:
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
写入CSV文件:
import csv
data = [['Name', 'Age'], ['John', 25], ['Jane', 30], ['Tom', 35]]
with open('data.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(data)
读取CSV文件并将数据存储为字典:
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
print(row)
写入字典数据到CSV文件:
import csv
data = [{'Name': 'John', 'Age': 25}, {'Name': 'Jane', 'Age': 30}, {'Name': 'Tom', 'Age': 35}]
fieldnames = ['Name', 'Age']
with open('data.csv', 'w', newline='') as file:
csv_writer = csv.DictWriter(file, fieldnames=fieldnames)
csv_writer.writeheader()
csv_writer.writerows(data)
对CSV数据进行排序:
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
sorted_rows = sorted(csv_reader, key=lambda row: row[1]) # 根据第二列进行排序
for row in sorted_rows:
print(row)
过滤CSV数据:
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
filtered_rows = filter(lambda row: int(row[1]) > 25, csv_reader) # 过滤年龄大于25的行
for row in filtered_rows:
print(row)
这些是一些基本的CSV数据处理方法,可以根据具体需求进行灵活运用。