[英]For loop that prints every line to a file. Error
I'm trying to make a for loop that prints every line in a list to a file, however I get this error. 我试图做一个for循环,将列表中的每一行打印到一个文件中,但是出现此错误。 Any help? 有什么帮助吗? Thanks 谢谢
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()
The error I get is: Python: TypeError: takes exactly 1 argument (2 given)
我得到的错误是: Python: TypeError: takes exactly 1 argument (2 given)
.write only accepts 1 parameter so i think you can do this .write只接受1个参数,所以我认为你可以做到这一点
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()
Since you are wirting a csv, why not use the csv
module. 由于您要使用csv,为什么不使用csv
模块。 Your method then becomes: 您的方法将变为:
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])
The with_statement
will automatically close the file, and the csv module has writerows
which does what it the name suggests. with_statement
将自动关闭文件,并且csv模块具有writerows
,其作用与名称相同。
In python write method of File takes only one argument whereas you are passing two. 在python中,File的write方法仅接受一个参数,而您要传递两个参数。
Either you can do outfile.write(" %s" %item) 您都可以执行outfile.write(“%s”%item)
Or better way is to use Pickle 或者更好的方法是使用泡菜
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.