csv文件读写处理

时间:2021-11-07 18:19:34

csv文件读写处理

 

1.读取

第一种:

 
import csv
with open("route.csv","r") as f:
#reader是一个迭代器
reader=csv.reader(f)
next(reader) #输出结果会去掉行头标题
for row in reader:
name=row[0]
dates=row[-1]
print({"name":name,"date":dates})
 

第二种:字典方式读取

 
import csv
with open("route.csv","r") as f:
#使用DictReader创建的reader是一个迭代器,遍历迭代器返回的数据是一个字典(有序字典)
#返回的结果不包含行首的标题
reader=csv.DictReader(f)
for row in reader:
# print(row) #遍历迭代器返回的数据是一个字典(有序字典)
print(row["昵称"],row["院系信息"])
 

2.写入

第一种:

 
import csv
headers=["username","age","addr"]
values={
("张三",23,"满城"),
("李四",24,"保定"),
("王五",25,"衡水"),
("赵六",26,"邯郸")
}
with open("name.csv","w",encoding="utf-8",newline="") as f: #newline换行符为空,默认为\n
writer=csv.writer(f)
writer.writerow(headers) #写入行首标题
writer.writerows(values) #写入多行
 

第二种:

 
import csv
headers=["username","age","addr"]
values=[
{"username":"张三","age":23,"addr":"保定"},
{"username":"李四","age":23,"addr":"邯郸"},
{"username":"王五","age":23,"addr":"石家庄"},
{"username":"赵六","age":23,"addr":"衡水"},
] with open("name2.csv","w",encoding="utf-8",newline="") as f:
writer=csv.DictWriter(f,headers)
#写入表头的时候需要写入writerheader方法
writer.writeheader()
writer.writerows(values)