使用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數據處理方法,可以根據具體需求進行靈活運用。