python - 用 Python 编写的 CSV 文件在每行之间有空行

标签 python windows csv

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

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

有没有办法让它不放额外的空行?

最佳答案

csv.writer 模块直接控制行尾,直接将\r\n 写入文件。在 Python 3 中,必须使用参数 'w', newline=''(空字符串)以非翻译文本模式打开文件,否则它将写入 \r\r\n 在 Windows 上,默认文本模式会将每个 \n 转换为 \r\n

#!python3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

Python 2 中,使用二进制模式打开 outfile,模式为 'wb' 而不是 'w' 防止 Windows 换行转换。 Python 2 也存在 Unicode 问题,并且需要其他变通方法来编写非 ASCII 文本。如果您必须在 Python 2 上将 Unicode 字符串写入 CSV,请参阅下面的 Python 2 链接以及页面末尾的 UnicodeReaderUnicodeWriter 示例,或者查看第三方unicodecsv模块:

#!python2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

文档链接

关于python - 用 Python 编写的 CSV 文件在每行之间有空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3348460/

相关文章:

c++ - Windows 上的 DLL 项目 : Unresolved External Symbol

json - 分离处理非常大的压缩 JSON 文件的命令的保存输出

python - 根据另一个数据框的列值过滤数据框

python - 如何从列表类别中对 pandas 数据框进行排序?

在不注册 WNDCLASS 的情况下创建窗口?

python - 写入 csv 时使用字典键作为坐标

xml - 如何向 PSCustomObject 添加值(XML 到 CSV 的转换)

python - 我编写了我的 Telegram Bot (用Python)提示用户发送图像。如何确保用户只发送图像而不发送其他内容?

python - 为新语言构建词性标注器

windows - 为 Windows 7 开发 : deployment seems an issue