1 import csv 2 3 4 def csv_rd(): 5 with open(r'E:anacondatestPythonDataaaaaa.csv','r',encoding='utf-8') as fp: 6 7 readers = csv.reader(fp) 8 print(type(readers)) 9 # next(readers) 10 # readers是一个迭代器,遍历这个迭代器返回的是一个列表 11 for x in readers: 12 name = x[2] 13 score = x[3] 14 print(name,score) 15 16 def csv_rd2(): 17 with open(r'E:anacondatestPythonDataaaaaa.csv', 'r', encoding='utf-8') as fp: 18 readers = csv.DictReader(fp) 19 #readers不会包含标题行的数据 20 # readers是一个迭代器,遍历这个迭代器返回的是一个字典 21 for x in readers: 22 print(x['学校名称'],x['总分']) 23 24 headers = ['name','age','height'] 25 values = [ 26 ('李梅',20,167), 27 ('lili',19,173), 28 ('tom',18,185) 29 ] 30 31 def write_csv1(): 32 with open(r'demo1.csv', 'w',encoding='utf-8',newline='') as fp: 33 #newline=''参数,默认写入一行数据以后换行 34 writers = csv.writer(fp) 35 #写入头部 36 writers.writerow(headers) 37 #写入数据 38 writers.writerows(values) 39 40 def write_csv2(): 41 value = [ 42 {'name':'张三','age':18,'height':180}, 43 {'name': '王五', 'age': 19, 'height': 175}, 44 {'name': '李四', 'age': 20, 'height': 168} 45 ] 46 with open(r'demo2.csv', 'w',encoding='utf-8',newline='') as fp: 47 #newline=''参数,默认写入一行数据以后换行 48 writers = csv.DictWriter(fp,headers) 49 #调用writeheader()方法写入变量名 50 writers.writeheader() 51 writers.writerows(value) 52 53 if __name__ == '__main__': 54 write_csv2()