python读取CSV文件以及“写入CSV致文件每一行后面会多一个空行”问题解决

原文链接:python读取CSV文件

python中有一个读写csv文件的包,直接import csv即可。利用这个python包可以很方便对csv文件进行操作,一些简单的用法如下。

1. 读文件

csv_reader = csv.reader(open('data.file', encoding='utf-8'))
    for row in csv_reader:
        print(row)

例如有如下的文件

输出结果如下

['0.093700','0.139771','0.062774','0.007698']

['-0.022711','-0.050504','-0.035691','-0.065434']

['-0.090407','0.021198','0.208712','0.102752']

['-0.085235','0.009540','-0.013228','0.094063']

可见csv_reader把每一行数据转化成了一个list,list中每个元素是一个字符串


2. 写文件

读文件时,我们把csv文件读入列表中,写文件时会把列表中的元素写入到csv文件中。

list = ['1', '2','3','4']
out = open(outfile, 'w') csv_writer = csv.writer(out) csv_writer.writerow(list)

可能遇到的问题:直接使用这种写法会导致文件每一行后面会多一个空行

解决办法如下:

out = open(outfile, 'w', newline='')
csv_writer = csv.writer(out, dialect='excel')
csv_writer.writerow(list)

参考如下:

在stackoverflow上找到了比较经典的解释,原来 python3里面对 str和bytes类型做了严格的区分,不像python2里面某些函数里可以混用。所以用python3来写wirterow时,打开文件不要用wb模式,只需要使用w模式,然后带上newline=''。 

In Python 2.X, it was required to open the csvfile with 'b' because the csv module does its own line termination handling.

In Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode strings. The correct way to open a csv file for writing is:

outputfile=open("out.csv",'w',encoding='utf8',newline='')

encoding can be whatever you require, but newline='' suppresses text mode newline handling. On Windows, failing to do this will write \r\r\n file line endings instead of the correct \r\n. This is mentioned in the 3.X csv.reader documentation only, but csv.writer requires it as well.

链接:http://blog.csdn.net/lixiang0522/article/details/7755059

其他链接:

python读写csv

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值