简体   繁体   English

无法使用 writerows 在 csv 文件中写入列表

[英]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.我试图在一个 csv 文件中写入几个列表的内容,但我不断收到错误消息。

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'" “AttributeError: '_io.TextIOWrapper' 对象没有属性 'writerows'”

The error is in the csvFile.writerows(header) line.错误在csvFile.writerows(header)行中。

I've Googled a lot and you're supposed to be able to use writerows to input a list into csv, no?我在谷歌上搜索了很多,你应该能够使用 writerows 将列表输入到 csv 中,不是吗?

Not quite - you need the csv module to operate on your file-object:不完全是 - 您需要csv 模块来操作您的文件对象:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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