csv文件读取
csv文件读取文章目录csv文件读取第一种方式:列表第二种方式:字典CSV文件写入第一种方式:列表第二种方式:字典第一种方式:列表示例:import csvwith open("stock.csv",'r',encoding='GBK') as fp:reader=csv.reader(fp)for x in reader:print(x)打印所有:注意:如果想要打印某一项则 用 print(x[
·
csv文件读取
第一种方式:列表
示例:
import csv
with open("stock.csv",'r',encoding='GBK') as fp:
reader=csv.reader(fp)
for x in reader:
print(x)
打印所有:
注意:如果想要打印某一项则 用 print(x[3]) 打印第三列的所有
第二种方式:字典
with open("stock.csv",'r',encoding='GBK') as fp:
reader=csv.DictReader(fp)
for x in reader:
print(x['secShortName'])#secShortName 代表某一个列的名字
打印结果:
CSV文件写入
第一种方式:列表
import csv
header=('name','age','height')#表头
students=[
('张三',18,180),
('李四', 19, 175),
('王五', 20, 180)
]
with open("student.csv",'w',encoding='utf-8',newline='') as fp:
writer=csv.writer(fp)
writer.writerow(header)#写入表头
writer.writerows(students)#写入内容
结果:
第二种方式:字典
import csv
header=('name','age','height')#表头
students=[
{'name':'张三','age':18,'height':180},
{'name':'李四','age': 19,'height': 175},
{'name':'王五','age': 20,'height': 180}
]
with open("student.csv",'w',encoding='utf-8',newline='') as fp:
writer=csv.DictWriter(fp,header)
#虽然DictWriter创建的时候有一个header,但是想要写进去数据,还是需要调用 writer.writeheader()方法
writer.writeheader()
writer.writerows(students)#写入内容
结果:
更多推荐
已为社区贡献2条内容
所有评论(0)