CSV写文件
import csv
file=open('d:/csv1.csv','a',newline='') #newline确保写入时没有空白的行
csvwriter=csv.writer(file)
s1=['james','male','39']
s2=(['vera','female','39'],['jacky','male','37'])
s3=[('vera','female','39'),('jacky','male','37')] #tuple/list可以嵌套使用
csvwriter.writerow(s1)
csvwriter.writerows(s2)
csvwriter.writerows(s3)
# fp.writerows(['vera','female','39'],['jacky','male','37'])#wrong, two args
file.close()
CSV读文件
import csv
with open('d:/coronavirus2019china.csv','r') as f:
reader=csv.reader(f) #以列表形式输出
for i in reader:
print(i)
f1=open('d:/coronavirus2019china.csv','r')
reader1=csv.DictReader(f1) #以字典形式输出
for i in reader1:
if int(i['confirm'])>100: #根据字段筛选后打印
print(i)
打印的部分结果如下,分别为列表格式和字典格式。
[‘新疆’, ‘76’, ‘0’, ‘1’, ‘1.32’]
[‘内蒙古’, ‘75’, ‘0’, ‘0’, ‘0.00’]
[‘宁夏’, ‘71’, ‘0’, ‘0’, ‘0.00’]
[‘香港’, ‘68’, ‘0’, ‘2’, ‘2.94’]
[‘台湾’, ‘24’, ‘0’, ‘1’, ‘4.17’]
[‘青海’, ‘18’, ‘0’, ‘0’, ‘0.00’]
[‘澳门’, ‘10’, ‘0’, ‘0’, ‘0.00’]
[‘西藏’, ‘1’, ‘0’, ‘0’, ‘0.00’]
OrderedDict([(‘province’, ‘湖北’), (‘confirm’, ‘62442’), (‘suspect’, ‘0’), (‘dead’, ‘2144’), (‘deadrate’, ‘3.43’)])
OrderedDict([(‘province’, ‘广东’), (‘confirm’, ‘1333’), (‘suspect’, ‘0’), (‘dead’, ‘5’), (‘deadrate’, ‘0.38’)])
OrderedDict([(‘province’, ‘河南’), (‘confirm’, ‘1267’), (‘suspect’, ‘0’), (‘dead’, ‘19’), (‘deadrate’, ‘1.50’)])
OrderedDict([(‘province’, ‘浙江’), (‘confirm’, ‘1203’), (‘suspect’, ‘0’), (‘dead’, ‘1’), (‘deadrate’, ‘0.08’)])
OrderedDict([(‘province’, ‘湖南’), (‘confirm’, ‘1011’), (‘suspect’, ‘0’), (‘dead’, ‘4’), (‘deadrate’, ‘0.40’)])
OrderedDict([(‘province’, ‘安徽’), (‘confirm’, ‘988’), (‘suspect’, ‘0’), (‘dead’, ‘6’), (‘deadrate’, ‘0.61’)])
OrderedDict([(‘province’, ‘江西’), (‘confirm’, ‘934’), (‘suspect’, ‘0’), (‘dead’, ‘1’), (‘deadrate’, ‘0.11’)])