Python 标准库 csv —— csv 文件的读写

来源:互联网 发布:午夜美女软件 编辑:程序博客网 时间:2024/06/07 03:52

csv 文件,逗号分割文件。

1. 写入并生成 csv 文件

注意这里是写入并生成,而非创建并写入,也即可自动创建一个不存在的 csv 文件。

import csvwith open('test.csv', 'w') as f:    writer = csv.writer(f)    # 写入表头,表头是单行数据    writer.writerow(['name', 'age', 'tel'])    data = [        ('zhangsan', 20, 'xxxx'),        ('lisi', 22, 'xxxx')    ]    # 写入这些多行数据    writer.writerows(data)

注意文件的打开模式,如果with open('', 'wb') 的方式打开,向其中写入字符内容时,很容易出现TypeError: a bytes-like object is required, not 'str' when writing to a file的类型错误。详细内容见python 3.5: TypeError: a bytes-like object is required, not ‘str’ when writing to a file

0 0