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)
这段代码读取file.csv,进行修改,并将结果写入到file_subset1。
然而,当我在Microsoft Excel中打开结果csv时,每条记录后都有一个额外的空行!
有没有办法让它不放额外的空行?
我使用writerow
def write_csv(writer, var1, var2, var3, var4):
"""
write four variables into a csv file
"""
writer.writerow([var1, var2, var3, var4])
numbers=set([1,2,3,4,5,6,7,2,4,6,8,10,12,14,16])
rules = list(permutations(numbers, 4))
#print(rules)
selection=[]
with open("count.csv", 'w',newline='') as csvfile:
writer = csv.writer(csvfile)
for rule in rules:
number1,number2,number3,number4=rule
if ((number1+number2+number3+number4)%5==0):
#print(rule)
selection.append(rule)
write_csv(writer,number1,number2,number3,number4)
我将这个答案w.r.t.写入python 3,因为我最初遇到了相同的问题。
我应该使用PySerial从arduino获取数据,并将它们写入.csv文件中。在我的例子中,每次读取都以'\r\n'结束,因此换行符总是分隔每行。
在我的例子中,newline= "选项不起作用。因为它显示了一些错误,比如:
with open('op.csv', 'a',newline=' ') as csv_file:
ValueError: illegal newline value: ''
所以他们似乎不接受省略换行符。
只在这里看到一个答案,我提到了writer对象中的行结束符,比如,
Writer = csv。Writer (csv_file, delimiter=' ',lineterminator='\r')
这对我跳过额外的换行很有效。