一、生成csv文件
- 使用
writerow
写入数据
import csv
datas = [
('小明',18,13100),
('小华',22,13101),
('小五',23,13102),
('小李',16,13103)
]
with open('demo.csv', mode='w', encoding='utf-8', newline='') as fw:
writer = csv.writer(fw)
for data in datas:
writer.writerow(data)
- 使用
writerows
写入数据
import csv
datas = [
('小明',18,13100),
('小华',22,13101),
('小五',23,13102),
('小李',16,13103)
]
with open('demo.csv', mode='w', encoding='utf-8', newline='') as fw:
writer = csv.writer(fw)
writer.writerows(data)
- 写入时要加上
newline=''
,不然windows系统会出现空行; writerow
表示单行写入,待写入数据为可迭代数据;writerows
表示多行写入;源码中待写入的数据格式为Iterable[Interable [Any]]
;源码如下:
二、读取csv文件
(1) 读取每一行数据
with open('demo.csv',mode='r',encoding='utf-8') as fr:
reader = csv.reader(fr)
for line in reader:
print(line)
输出结果
['小明', '18', '13100']
['小华', '22', '13101']
['小五', '23', '13102']
['小李', '16', '13103']
(2) 读取某列数据
with open('demo.csv',mode='r',encoding='utf-8') as fr:
reader = csv.reader(fr)
for line in reader:
print(line[1]) # 读取第二列数据
输出结果
18
22
23
16
(3) 读取某多列数据
例:读取第二列、第三列数据
with open('demo.csv',mode='r',encoding='utf-8') as fr:
reader = csv.reader(fr)
for line in reader:
print(line[1:3])
输出结果
['18', '13100']
['22', '13101']
['23', '13102']
['16', '13103']