【发布时间】:2014-06-06 00:55:04
【问题描述】:
我一直在使用多个代码 sn-ps 来创建一个解决方案,该解决方案允许我将足球队中的球员列表写入 csv 文件。
import csv
data = []
string = input("Team Name: ")
fName = string.replace(' ', '') + ".csv"
print("When you have entered all the players, press enter.")
# while loop that will continue allowing entering of players
done = False
while not done:
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ")
print (string)
file = open(fName, 'w')
output = csv.writer(file)
for row in string:
tempRow = row
output.writerow(tempRow)
file.close()
print("Team written to file.")
我希望导出的 csv 文件如下所示:
player1,25,striker
player2,27,midfielder
等等。但是,当我检查导出的 csv 文件时,它看起来更像这样:
p
l
a
y
e
r
,
2
5
等等。
有人知道我哪里出错了吗?
非常感谢 卡尔
【问题讨论】:
-
写入 CSV 文件时不需要
tempRow。此外,您应该使用newline=''参数打开文件(docs.python.org/3/library/csv.html#csv.writer - 您还会在那里找到解释)。在您的情况下可能无关紧要,但有一天可能会很重要......所以,习惯吧:)
标签: list csv python-3.x export-to-csv