使用writerow方法给csv文件写入内容。
open()函数如果没有设定 newline=’’ (空字符串),表格中会隔一行写一行。
然后创建一个writer对象。writerow()方法可以写入一行,writerows()方法可以写入多行。

writerow()
import csvpersons = [('Tom', 20, 180), ('Allen', 21, 182), ('Jerry', 22, 181)]
headers = ('name', 'age', 'height')
with open('persons.csv', 'w', encoding='utf-8', newline='') as f:  
    write = csv.writer(f)  # 创建writer对象
    write.writerow(headers)
    # 写内容,writerrow 一次只写入一行
    for data in persons:
        write.writerow(data)writerows()


一次性写入多行,不用遍历。

persons = [('Tom', 20, 180), ('Allen', 21, 182), ('Jerry', 22, 181)]
headers = ('name', 'age', 'height')
with open('persons2.csv', 'w', encoding='utf-8', newline='') as f:
    write = csv.writer(f)
    write.writerow(headers)
# 写内容,writerows,一次写入多行内容
	write.writerows(persons)DictReader()


写入字典数据。

persons = [
    {'name': 'Tom', 'age': 20, 'height': 180},
    {'name': 'Allen', 'age': 21, 'height': 182},
    {'name': 'Jerry', 'age': 22, 'height': 181},
]
# 数据的keys要跟表头对应,数量也要保持一致,否则会报错
headers = ('name', 'age', 'height')
with open('persons3.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.DictWriter(f, headers)
    writer.writeheader()
    writer.writerows(persons)


CSV读取
两种方法:

with open('persons.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    print(reader, type(reader))   # <_csv.reader object at 0x000001D5AEF6B518>
    for i in reader:
        print(i)


程序运行结果:

with open('persons.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    print(reader, type(reader))   # <_csv.reader object at 0x000001D5AEF6B518>
    for i in reader:
        print(i['age'])