用 Python 编写的 CSV 文件每行之间有空行 | 您所在的位置:网站首页 › 喀什的红枣什么时候成熟采摘 › 用 Python 编写的 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 时,每条记录后都会有一个额外的空白行! 有没有办法让它不放一个额外的空行? Answerscsv.writer模块直接控制行尾,直接将\r\n写入文件。在 Python 3 中,必须使用参数'w', newline=''(空字符串)以未翻译文本模式打开文件,否则它将在 Windows 上写入\r\r\n,默认文本模式会将每个\n转换为\r\n。 #!python3 with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile: writer = csv.writer(outfile)在 Python 2 中,使用二进制模式以'wb'模式而不是'w'模式打开outfile以防止 Windows 换行符转换。 Python 2 也存在 Unicode 问题,并且需要其他变通方法来编写非 ASCII 文本。如果您必须在 Python 2 上将 Unicode 字符串写入 CSV,请参阅下面的 Python 2 链接以及页面末尾的UnicodeReader和UnicodeWriter示例,或者查看第 3 方unicodecsv模块: #!python2 with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile: writer = csv.writer(outfile) 文档链接https://docs.python.org/3/library/csv.html#csv.writer https://docs.python.org/2/library/csv.html#csv.writer |
CopyRight 2018-2019 实验室设备网 版权所有 |