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 链接以及页面末尾的 UnicodeReader
和 UnicodeWriter
示例,或者查看第三方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/