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时,每条记录后都有一个额外的空行!
有没有办法让它不放额外的空行?
使用下面定义的方法将数据写入CSV文件。
open('outputFile.csv', 'a',newline='')
只需在open方法中添加一个额外的newline= "参数:
def writePhoneSpecsToCSV():
rowData=["field1", "field2"]
with open('outputFile.csv', 'a',newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(rowData)
这将写入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)
csv。Writer模块直接控制行结束符,并直接将\r\n写入文件。在python3中,该文件必须以非翻译文本模式打开,参数为'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链接以及页面末尾的unicoderreader和UnicodeWriter示例,或者查看第三方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