目录
1 写文件
2 读文件
3 方言
4 使用字段名
官方文档: https://docs.python.org/3.7/library/csv.html
The csv module’s reader and writer objects read and write sequences.
Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.
对于序列的读写: reader, writer 对象。
dir(csv) #最重要的2个方法是 reader() 和 writer()
对于字典的读写: DictReader and DictWriter 类。
1. 写数据
import csv
headers = ['class','name','sex','height','age']
rows = [
[1,'Tom','male',168,23],
[1,'Jim','female',162,22],
[2,'lili','female',163,21],
[2,'lucy','male',158,21]
]
with open('dustbin/test.csv','w')as f:
f_csv = csv.writer(f)
f_csv.writerow(headers) #写一行
f_csv.writerows(rows) #写多行
# 如果有空行,请设置 newline 参数
# with open('test.csv','w',newline='')as f:
检查
$ cat dustbin/test.csv
class,name,sex,height,age
1,Tom,male,168,23
1,Jim,female,162,22
2,lili,female,163,21
2,lucy,male,158,21
2. 读入数据
import csv
with open('dustbin/test.csv')as f:
f_csv = csv.reader(f)
for row in f_csv:
print(" ".join(row))
输出
class name sex height age
1 Tom male 168 23
1 Jim female 162 22
2 lili female 163 21
2 lucy male 158 21
(2) 还可以读取字符串
import csv
for row in csv.reader(['one,two,three']):
print(row)
输出: ['one', 'two', 'three']
3. 使用方言定义文件类型
import csv
# 定义一个方言:分隔符是冒号,不带引号
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('/etc/passwd', newline='') as f:
reader = csv.reader(f, dialect='unixpwd')
for row in reader:
print(row)
输出
['root', 'x', '0', '0', 'root', '/root', '/bin/bash']
['daemon', 'x', '1', '1', 'daemon', '/usr/sbin', '/usr/sbin/nologin']
['bin', 'x', '2', '2', 'bin', '/bin', '/usr/sbin/nologin']
['sys', 'x', '3', '3', 'sys', '/dev', '/usr/sbin/nologin']
['sync', 'x', '4', '65534', 'sync', '/bin', '/bin/sync']
4. 使用字段名读写字典类型
(1) 字典数据写入csv文件
dt1={"item":"apple", "price": 5}
dt1s=[
{"item":"banana", "price": 4},
{"item":"orange", "price": 3},
{"item":"pumpkin", "price": 1}
]
import csv
fw=open("dustbin/test2.csv", 'w')
writer=csv.DictWriter(fw, fieldnames=["item", "price"])
writer.writeheader()
writer.writerow( dt1 )
writer.writerows( dt1s )
fw.close()
查看数据
$ cat dustbin/test2.csv
item,price
apple,5
banana,4
orange,3
pumpkin,1
(2) 读取字典
import csv
with open('dustbin/test2.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['item'], row['price'])
输出
apple 5
banana 4
orange 3
pumpkin 1