简体   繁体   中英

Cannot write list in csv file using writerows

I'm trying to write the contents of a few lists in a csv file, but I keep getting errors.

My code is:

def saveLeague(csvLink, listOfLeague):
    '''clears the csv-file and replaces it with the stats from your list'''

    header = ['Team', 'GP', 'W', 'L', 'OTL', 'PTS', 'GF', 'GA', 'Plus minus', 'Division']
    sortLeague(listOfLeague)

    with open(csvLink, 'w') as csvFile:
        csvFile.truncate() #clear the csv file

        csvFile.writerows(header) #imput Team, GP, W, L and so on in row 1

        for team in listOfLeague:
            info = returnTeam(team) # info is a list of ints and str 
            csvFile.writerows(info)
    return

The error message I get is

"AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows'"

The error is in the csvFile.writerows(header) line.

I've Googled a lot and you're supposed to be able to use writerows to input a list into csv, no?

Not quite - you need the csv module to operate on your file-object:

import csv 


csvLink = "t.txt"
header = ['Team', 'GP', 'W', 'L', 'OTL', 'PTS', 'GF', 'GA', 'Plus minus', 'Division']
info   = [ list(range(10)), list(range(10,20))] # some data

with open(csvLink, 'w', newline = "") as f:   # "w" already truncates, you need newline = ""

    csvFile = csv.writer(f)        # the module does the writing
    csvFile.writerow(header)       #  only writerow - not rows

    # no loop needed, write all of info
    csvFile.writerows(info)    # write all data

Doku:

Output:

Team,GP,W,L,OTL,PTS,GF,GA,Plus minus,Division
0,1,2,3,4,5,6,7,8,9
10,11,12,13,14,15,16,17,18,19 

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