简体   繁体   中英

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. 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)

.write only accepts 1 parameter so i think you can do this

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. 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.

In python write method of File takes only one argument whereas you are passing two.

Either you can do outfile.write(" %s" %item)

Or better way is to use Pickle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM