本文实例讲述了Python实现的简单读写csv文件操作。分享给大家供大家参考,具体如下:
python中有一个读写csv文件的包,直接import csv
即可
新建test.csv
1.写
1
2
3
4
5
|
import csv with open ( "test.csv" , "w" ,encoding = 'utf8' ) as csvfile: writer = csv.writer(csvfile) writer.writerow([ "index" , "a_name" , "b_name" ]) writer.writerows([[ 0 , 'a1' , 'b1' ],[ 1 , 'a2' , 'b2' ],[ 2 , 'a3' , 'b3' ]]) |
直接使用这种写法会导致文件每一行后面会多一个空行
解决的方法
用python3来写wirterow时,打开文件时使用w模式,然后带上newline=''
1
2
3
4
5
|
import csv with open ( "test.csv" , "w" ,encoding = 'utf8' ,newline = '') as csvfile: writer = csv.writer(csvfile) writer.writerow([ "index" , "a_name" , "b_name" ]) writer.writerows([[ 0 , 'a1' , 'b1' ],[ 1 , 'a2' , 'b2' ],[ 2 , 'a3' , 'b3' ]]) |
2.读
1
2
3
4
5
|
import csv with open ( "test.csv" , "r" ) as csvfile: reader = csv.reader(csvfile) for line in reader: print (line) |
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://www.cnblogs.com/baby123/p/8078508.html