【问题标题】:Python CSV export writing characters to new linesPython CSV 将写入字符导出到新行
【发布时间】: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


【解决方案1】:

您的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

也是如此

【讨论】:

  • 感谢您的帮助!我已经对它们进行了更改,现在效果好多了。虽然输出文件现在显示p,l,a,y,e,r,1,2,5,s,t,r,i,k,e,r,。无论如何要纠正它,使其按预期显示?谢谢
  • @karldou 检查我更新的答案。我已经摆脱了 CSV 写入,并在 `string += input("Position: ") + '\n'` 行上添加了一个新行字符
  • 太棒了!非常感谢,现在完美运行!真的很感激!
猜你喜欢
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2020-10-27
相关资源
最近更新 更多