字典方式的读取更为简单,最好都掌握,看情形而用
import csv
def csv_reader_demo1():
with open(‘logo.csv’, ‘r’) as f:
reader = csv.reader(f)
for x in reader:
print(x)
def csv_reader_demo2():
with open(‘logo.csv’,‘r’) as f:
reader=csv.DictReaderreader(f)
for x in reader:
print(x)
def csv_writer_demo1():
headers=[‘username’,‘age’,‘height’]
values=[
(‘张三’,‘20’,‘180’),
(‘李四’,‘19’,‘175’)
]
with open(‘wzq.csv’,‘w’,encoding=‘utf-8’,newline="") as fp:
writer = csv.writer(fp)
writer.writerow(headers)
writer.writerows(values)
def csv_writer_demo2():
headers=[‘username’,‘age’,‘height’]
values=[
{‘username’:‘张三’,‘age’:18,‘height’:180},
{‘username’: ‘李四’, ‘age’: 18, ‘height’: 181}
]
with open(‘wzq1.csv’,‘w’,encoding=‘utf-8’,newline="") as fp:
writer = csv.DictWriter(fp,headers)
writer.writeheader()
writer.writerows(values)
if name == ‘main’:
csv_reader_demo1()
csv_reader_demo2()
csv_writer_demo1()
csv_writer_demo2()