用 Python 编写的 CSV 文件每行之间有空行 [英] CSV file written with Python has blank lines between each row
问题描述
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[10]] += 1
with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
writer = csv.writer(outfile)
for row in data:
if counter[row[10]] >= 504:
writer.writerow(row)
此代码读取thefile.csv
,进行更改,并将结果写入thefile_subset1
.
This code reads thefile.csv
, makes changes, and writes results to thefile_subset1
.
但是,当我在 Microsoft Excel 中打开生成的 csv 时,每条记录后面都有一个额外的空行!
However, when I open the resulting csv in Microsoft Excel, there is an extra blank line after each record!
有没有办法让它不多放一个空行?
Is there a way to make it not put an extra blank line?
推荐答案
在 Python 2 中,使用 'wb'
而不是 'w' 模式打开
outfile
代码>.csv.writer
直接将
写入文件.如果你不以 binary 模式打开文件,它会写
因为在 Windows 上 text 模式会翻译每个
转化为
.
In Python 2, open outfile
with mode 'wb'
instead of 'w'
. The csv.writer
writes
into the file directly. If you don't open the file in binary mode, it will write
because on Windows text mode will translate each
into
.
在 Python 3 中,所需的语法发生了变化(请参阅下面的文档链接),因此请改为使用附加参数 newline=''
(空字符串)打开 outfile
.>
示例:
In Python 3 the required syntax changed (see documentation links below), so open outfile
with the additional parameter newline=''
(empty string) instead.
# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
writer = csv.writer(outfile)
# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
文档链接
- https://docs.python.org/2/library/csv.html#csv.writer
- https://docs.python.org/3/library/csv.html#csv.writer
这篇关于用 Python 编写的 CSV 文件每行之间有空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!