使用Python内置的CSV模块处理CSV文件如下:
- 打开CSV文件:
import csv
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
- 将CSV文件转换为列表:
import csv
with open('example.csv', 'r') as file:
reader = csv.reader(file)
csv_list = list(reader)
- 将CSV文件转换为字典:
import csv
with open('example.csv', 'r') as file:
reader = csv.DictReader(file)
csv_dict_list = list(reader)
- 筛选和排序数据:
import csv
with open('example.csv', 'r') as file:
reader = csv.DictReader(file)
filtered_rows = []
for row in reader:
if row['column1'] == 'value1' and row['column2'] == 'value2':
filtered_rows.append(row)
sorted_rows = sorted(filtered_rows, key=lambda x: x['column3'])