csv文件,一行为一条数据,数据字段用逗号‘,’分隔
可以使用记事本、EXcel等方式打开
csv文件的读写都有两种方式:列表或字典(推荐字典)
import csv # 导入内置的csv模块
列表形式 | 每条数据时一个列表 |
---|
csv.reader(f) | 创建read对象 |
csv.writer(f) | 创建write对象 |
def csv_read_list():
with open('test.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
title = next(reader)
print(title)
for i in reader:
print(i)
def csv_write_list():
headers = ['name', 'age', 'height']
data1 = ['张三', 18, 180]
data2 = ['da张三', 12, 170]
with open('test.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerow(data1)
writer.writerow(data2)
字典形式 | 每条数据时一个字典 |
---|
csv.DictReader(f) | 创建read对象 |
csv.DictWriter(f) | 创建write对象 |
def csv_read_dict():
with open('test.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for i in reader:
print(i)
def csv_write_dict():
headers = ['name', 'age', 'height']
data1 = {'name': '张三', 'age': 18, 'height': 180}
data2 = {'name': '张da三', 'age': 12, 'height': 170}
with open('test.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, headers)
writer.writeheader()
writer.writerow(data1)
writer.writerow(data2)