python3 csv

python3 输入输出csv文件的2种形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

import csv

def testCSVWriterReader():
with open('csvtest.csv','w',newline='') as cf:
cw = csv.writer(cf,delimiter=',')
cw.writerow(['aa','bb','cc'])
cw.writerow(["aa"]*5+['ff'])
cf.close()

with open('csvtest.csv','r') as f:
cr = csv.reader(f,delimiter=',')
for row in cr:
print(row)
for d in row:
print(d,' ')
f.close()

def testCSVDic():
with open('csv_dict.csv','w') as cf:
csvhead = ['id','title'] # write head
writer = csv.DictWriter(cf,fieldnames=csvhead)
writer.writeheader();
writer.writerow({'id': '1', 'title': 'aa'})
writer.writerow({'id': '2', 'title': 'bb'})

with open('csv_dict.csv') as cf:
reader = csv.DictReader(cf)
for row in reader:
print(row['id'],row['title'])



print('testing writer and reader for csv file......')
testCSVWriterReader()

print('testing dic writer and dic reader for csv file..... ')
testCSVDic()