python写csv文件前面的0消失_Python写入CSV文件的问题

这篇文章主要是前几天我处理数据时遇到的三个问题:

Python写入的csv的问题

Python2与Python3处理写入写入空行不同的处理方式

Python与Python3的编码问题

其实上面第3个问题是一个大问题,本文暂且不表,主要说明前两个问题。

第一个问题###

先看一下官方文档给出的例子:

headers = ['Symbol','Price','Date','Time','Change','Volume']

rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),

('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),

('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),

]

with open('stocks.csv','w') as f:

f_csv = csv.writer(f)

f_csv.writerow(headers)

f_csv.writerows(rows)

但是上述代码并不能得到我们想要的格式,它是横着排的,其实excel只有一行数据。

无奈,我不知道问题出在哪里,我只能一行行的写入。

for i in range(0, len(list)):

f_csv.writerow(list[i])

第二个问题###

关于写入excel时,文档多出空行的问题,python2和3有不同的处理。

先看Python2,以二进制wb的方式写入即可。

writefile = open('result.csv','wb')

writer = csv.writer(writefile)

Python3使用上述方式会报错:TypeError: 'str' does not support the buffer interface

解决方法如下:以w模式打开文件,添加参数newline=''

outputfile=open("out.csv",'w',encoding='utf8',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][2] documentation only, but [csv.writer][3] requires it as well.

**

参考###

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值