csv Writer(cvs)将每个字符视为一个字段

dzjeubhm  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(151)

Writer正在将列表写入csv文件,但将每个字符视为一个字段:

nteams =16
c = 1
teams = []

while c <= nteams:
    teams.append("Team " + str(c))
    c = c + 1

此位正确创建列表,并返回以下teams

['Team 1', 'Team 2', 'Team 3', 'Team 4']

然后我这样做:

import csv

# writing the data into the file
with open ('teams.csv','w') as f:
    wtr = csv.writer(f)
    wtr.writerows(teams)

但是这个位将这个返回到csv文件:

T,e,a,m, ,1
T,e,a,m, ,2
T,e,a,m, ,3
T,e,a,m, ,4

情况不妙,请帮帮我.
我试过更改打开模式“WB”和“W”:

with open ('teams.csv','w') as f:
                        ^
4ioopgfo

4ioopgfo1#

writerows方法需要一个列表的列表。您传递给它的是一个字符串列表。您可以使用列表解析来创建列表的列表:

import csv

nteams =16
c = 1
teams = []

while c <= nteams:
    teams.append("Team " + str(c))
    c = c + 1

with open ('teams.csv','w') as f:
    wtr = csv.writer(f)
    wtr.writerows([[team] for team in teams])

输出:

Team 1
Team 2
Team 3
Team 4

相关问题