Python: 对CSV文件读写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python: 对CSV文件读写相关的知识,希望对你有一定的参考价值。

1. python 有专门的csv包,直接导入即可。

import csv;

2. 直接使用普通文件的open方法

csv_reader=open("e:/python/csv_data/log.csv" , ‘r‘)
data=[]
for line in csv_reader:
    data.append(list(line.strip().split(‘|‘)))

for line in data:
    print(line)

3. 使用csv.reader & writer,返回迭代类型

import sys;

reload(sys)
sys.setdefaultencoding("utf-8");
csv_reader=csv.reader(file(‘E:\\\\Python\\CSV_data\\log.csv‘,‘rb‘))
for row in csv_reader:
    print(row)

writer=csv.writer(file(‘E:\\\\Python\\CSV_data\\log_write.csv‘,‘wb‘))
writer.writerow([‘name‘,‘id‘,‘comment‘])
lines=[range(3) for i in range(5)]
for line in lines:
    writer.writerow(line)

4.  使用 csv.DictReader & DictWriter, 返回dict 字典类型。

reader1=csv.DictReader(file(‘E:\\\\Python\\CSV_data\\women_write.csv‘,‘rb‘))

参考

以上是关于Python: 对CSV文件读写的主要内容,如果未能解决你的问题,请参考以下文章

在python中,如何更新CSV文件中超过5K行的值?

Python csv模块(读写文件)

python3使用csv模块读写csv文件

Python csv库整理(部分)

python读写csv文件

python3使用csv模块读写csv文件