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时,每条记录后都有一个额外的空白行!
有没有办法使它不放在多余的空白行?
#1楼
以二进制模式“ wb”打开文件在Python 3+中不起作用。 或者更确切地说,您必须在编写数据之前将数据转换为二进制。 那只是一个麻烦。
相反,您应该将其保留在文本模式下,但是将换行符替换为空。 像这样:
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
#2楼
注意:似乎这不是首选的解决方案,因为在Windows系统上如何