如何在 Python 中将列表保存到 CSV

Lor*_*ass 0 python csv save

我一直在尝试将我正在开发的冒险游戏的列表保存到 CSV 文件中,但我似乎找不到任何可以在线运行的内容,这是我拥有的代码,

import csv
testarray = ["Hello", "My", "Name", "is", "John"]
wtr = csv.writer(open ('test.csv', 'w'), delimiter=';', lineterminator='\n')
for x in testarray : wtr.writerow ([x])
for label in testarray:
  testarray.write([label])
print("Done!")

Run Code Online (Sandbox Code Playgroud)

对不起,如果这设置不好,我对此有点陌生。在此先感谢您的帮助

小智 5

在我发布答案之前,让我花时间解释一下你做错了什么,这样你就不会重复同样的坏习惯。

这行可以写得更好:

wtr = csv.writer(open ('test.csv', 'w'), delimiter=';', lineterminator='\n')
Run Code Online (Sandbox Code Playgroud)

Python它可以写成:

with open('items.csv', 'w', newline='') as csvfile:
Run Code Online (Sandbox Code Playgroud)

在您的代码示例中,您从未使用过with. 现在是阅读为什么应该使用它的好时机。

在此之下,您可以指定编写方式和内容,如下所示:

item_writer = csv.writer(csvfile, delimiter=', quoting=csv.QUOTE_MINIMAL)
Run Code Online (Sandbox Code Playgroud)

这个 for 循环可以写得更好:

for label in testarray:
  testarray.write([label])
Run Code Online (Sandbox Code Playgroud)

您不需要label[]括号将变量括起来,因为它不是list. 您正在引用list.

可以这样写:

for item in testarray:
    item_writer.writerow(item)
Run Code Online (Sandbox Code Playgroud)

这可能不是您想要的,因为它会将每个项目都写list在它自己的行上。

把所有东西放在一起,我们得到:

import csv


def main():

    testarray = ["Hello", "My", "Name", "is", "John"]

    with open('test.csv', mode='w') as employee_file:
        employee_writer = csv.writer(employee_file, delimiter=',',  quotechar='"', 
                                     quoting=csv.QUOTE_MINIMAL)
        employee_writer.writerow(testarray)

    print("done")

 # Will output:
 # Hello,My,Name,is,John

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)