我一直在使用多个代码段创建一个解决方案,允许我将足球队中的球员列表写入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
等等。
有没有人知道我哪里出错了?
非常感谢 卡尔
答案 0 :(得分:2)
您的string
是一个字符串。它不是字符串列表。当你这样做时,你期望它是一个字符串列表:
for row in string:
当您遍历字符串时,您将迭代其字符。这就是你每行看到一个角色的原因。
声明字符串列表。并将每个字符串附加到它上面:
done = False
strings_list = []
while not done:
string = ""
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ") + '\n'
strings_list.append(string)
现在迭代此strings_list
并打印到输出文件。由于您将自己的分隔符(逗号)放在字符串中,因此不需要csv编写器。
a_file = open(fName, 'w')
for row in strings_list:
print(row)
a_file.write(row)
a_file.close()
注意:强>
string
是Python中标准模块的名称。明智的做法是不要将它用作程序中任何变量的名称。您的变量file