用Python编写的CSV文件在每行之间有空行 [英] CSV file written with Python has blank lines between each row

查看:148
本文介绍了用Python编写的CSV文件在每行之间有空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  import csv 

with open('thefile.csv','rb')as f:
data = list(csv.reader f)
import collections
counter = collections.defaultdict(int)

数据行:
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)


b $ b

此代码读取 thefile.csv ,进行更改,并将结果写入 thefile_subset1 p>

但是,当我在Microsoft Excel中打开生成的csv时,每个记录后面都有一个额外的空行。



解决方案

在Python 2中,打开使用模式'wb'而不是'w'的输出文件 csv.writer 直接将 \r\\\
写入文件。如果您不以 binary 模式打开文件,则会写入 \r\r\\\
,因为在Windows上文本模式会将每个 \\\
翻译成 \r\\\



在Python 3中,所需的语法已更改,因此使用附加参数 newline =''打开 outfile / code>。



例如:



  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)
/ pre>

文档链接




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)

This code reads thefile.csv, makes changes, and writes results to thefile_subset1.

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?

解决方案

In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes \r\n into the file directly. If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

In Python 3 the required syntax changed, so open outfile with the additional parameter newline='' instead.

Examples:

# 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)

Documentation Links

这篇关于用Python编写的CSV文件在每行之间有空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆