我正在尝试创建一个for循环,将列表中的每一行打印到文件中,但是我收到此错误。有帮助吗?感谢
def write_file(filename, rabbitlist, foxlist, finallist, averagefox, averagerabbit):
# Opens File for Data Input
outfile = open(str(filename) + ".csv", 'w')
# Writes Data to Newly Created File
finalresult = "\n".join(", ".join(map(str, l)) for l in finallist)
outfile.write(str("Day, Foxes, Rabbits, , Average Foxes, Average Rabbits\n"))
lastline = [0, foxlist[0], rabbitlist[0], " ", averagefox, averagerabbit]
for item in lastline:
outfile.write(" %s", item)
outfile.close()
我得到的错误是:Python: TypeError: takes exactly 1 argument (2 given)
答案 0 :(得分:3)
。只写accepts 1 parameter所以我认为你可以这样做
def write_file(filename, rabbitlist, foxlist, finallist, averagefox, averagerabbit):
# Opens File for Data Input
outfile = open(str(filename) + ".csv", 'w')
# Writes Data to Newly Created File
finalresult = "\n".join(", ".join(map(str, l)) for l in finallist)
outfile.write(str("Day, Foxes, Rabbits, , Average Foxes, Average Rabbits\n"))
lastline = [0, foxlist[0], rabbitlist[0], " ", averagefox, averagerabbit]
for item in lastline:
outfile.write(" %s" % item)
outfile.close()
答案 1 :(得分:1)
由于您正在使用csv,为什么不使用csv
模块。然后你的方法变成:
import csv
def write_file(filename,
rabbitlist,
foxlist,
finallist,
averagefox,
averagerabbit):
header_row = ['Day','Foxes','Rabbits',' ','Average Foxes','Average Rabbits']
with open(filename,'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(header_row)
writer.writerows(finallist)
writer.writerow([0,
foxlist[0],
rabbitlist[0],
" ",
averagefox,
averagerabbit])
with_statement
会自动关闭文件,而csv模块会writerows
执行名称所示的操作。
答案 2 :(得分:0)
在python中,File的方法只接受一个参数,而你传递两个参数。
你可以做outfile.write(“%s”%item)
或者更好的方法是使用Pickle