0

我正在尝试创建一个 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)

4

3 回答 3

3

.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()
于 2013-06-19T04:06:16.337 回答
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其名称所暗示的功能。

于 2013-06-19T04:25:46.450 回答
0

在 Python 中 File 的 write 方法只接受一个参数,而您传递两个参数。

你可以做 outfile.write(" %s" %item)

或者更好的方法是使用 Pickle

于 2013-06-19T04:17:52.627 回答