这篇文章主要是前几天我处理数据时遇到的三个问题:
- 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
file line endings instead of the correct
. This is mentioned in the 3.X [csv.reader][2] documentation only, but [csv.writer][3] requires it as well.
**