python csv库
水一水又是一篇,乐
读取
import csv
# 打开 CSV 文件
with open('example.csv', mode='r', newline='') as file:
csv_reader = csv.reader(file)
# 读取文件头(可选)
headers = next(csv_reader)
print(f"Headers: {headers}")
# 读取每一行数据
for row in csv_reader:
print(row)
写入
import csv
# 要写入的数据
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
# 打开 CSV 文件
with open('output.csv', mode='w', newline='') as file:
csv_writer = csv.writer(file)
# 写入数据
csv_writer.writerows(data)
读取csv为字典
import csv
# 打开 CSV 文件
with open('example.csv', mode='r', newline='') as file:
csv_reader = csv.DictReader(file)
# 读取每一行数据
for row in csv_reader:
print(row)
写入字典到csv
import csv
# 要写入的数据
data = [
{'Name': 'Alice', 'Age': 30, 'City': 'New York'},
{'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'},
{'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
]
# 获取字典的键作为表头
fieldnames = data[0].keys()
# 打开 CSV 文件
with open('output.csv', mode='w', newline='') as file:
csv_writer = csv.DictWriter(file, fieldnames=fieldnames)
# 写入表头
csv_writer.writeheader()
# 写入数据
csv_writer.writerows(data)
处理带有特定分隔符的 CSV 文件
默认情况下,CSV 文件使用逗号作为分隔符,但你可以通过 delimiter
参数来指定其他分隔符,例如制表符(\t
)。
import csv
# 读取使用制表符分隔的 CSV 文件
with open('tab_separated.csv', mode='r', newline='') as file:
csv_reader = csv.reader(file, delimiter='\t')
# 读取每一行数据
for row in csv_reader:
print(row)
羊城杯2024 data-analy1
某位✌的wp
import csv
import re
p=[734, 735, 736, 737, 738, 739, 747, 748, 750, 751, 752, 757, 758, 759, 772,
778, 782, 783, 784, 787, 788, 795, 798, 730, 731, 732, 740, 745, 746, 755,
756, 766, 767, 771, 775, 776, 785, 786, 796, 733, 749, 753, 773, 774, 777,
780, 781, 789, 790, 791, 793, 799]
def cd(data,k):
if not isinstance(data,str):
return None
elif data.isdigit() and 1<= int(data) and int(data)<=10002:
return 0
elif data in ['男','女']:
return 4
elif re.search("[\u4e00-\u9fa5]",data[0]): # 中文范围
return 3
elif data.isdigit() and len(data)==8: # 出生日期
return 5
elif len(data)==32: #
return 2
elif len(data)==18 and data[6:14] in k: # 身份证与出生日期对应
return 6
elif len(data)==11 and data.isdigit() and int(data[0:3]) in p: # 手机号
return 7
else:
return 1
rows=[]
with open('C:\\Users\\21609\\Downloads\\Compressed\\data-analy1的附件\\tempdir\\DS附件\\附件\\person_data.csv','r',encoding='utf-8') as fp:
csv_reader=csv.reader(fp)
for num,row in enumerate(csv_reader,start=1):
if row== ['编号', '用户名', '密码', '姓名', '性别', '出生日期', '身份证号', '手机号码']:
rows.append(row)
continue
new=[0]*8
for i in row:
new[cd(i,row)]=i
rows.append(new)
with open('C:\\Users\\21609\\Downloads\\Compressed\\data-analy1的附件\\tempdir\\DS附件\\附件\\person_data_new.csv',mode='w',newline="",encoding='utf-8') as fp:
#newline指定行尾,默认为\r\n
csv_writer = csv.writer(fp)
csv_writer.writerows(rows)
数据->从文本/csv->导入,可看到编码正确的文档