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

时间:2019-04-12 16:32:31

标签: python python-3.x csv

我正在尝试将一些列表的内容写到一个csv文件中,但是我总是遇到错误。

我的代码是:

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

我收到的错误消息是

  

“ AttributeError:'_io.TextIOWrapper'对象没有属性   'writerows'“

错误在csvFile.writerows(header)行中。

我已经用Google搜索了很多,应该可以使用writerows将列表输入到csv中,不是吗?

1 个答案:

答案 0 :(得分:1)

不太完全-您需要the csv module才能对文件对象进行操作:

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:

输出:

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