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

我一直在尝试将我正在开发的冒险游戏的列表保存为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!")

很抱歉,如果设置的不好,我对此很陌生。预先感谢您的帮助

a409788679 回答:如何在Python中将列表保存到CSV

在我发布答案之前,让我花点时间解释您在做错什么,以免您重复同样的不良习惯。

这行可能写得更好:

wtr = csv.writer(open ('test.csv','w'),delimiter=';',lineterminator='\n')

Python中,它可以写为:

with open('items.csv','w',newline='') as csvfile:

在代码示例中,您从未使用过with。现在是阅读why you should use it的好时机。

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

item_writer = csv.writer(csvfile,delimiter=',quoting=csv.QUOTE_MINIMAL)

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

for label in testarray:
  testarray.write([label])

您不必将label变量括在[]括号中,因为它不是list。您正在引用list中的项目。

它可以这样写:

for item in testarray:
    item_writer.writerow(item)

这可能不是您想要的,因为它会将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,',quotechar='"',quoting=csv.QUOTE_MINIMAL)
        employee_writer.writerow(testarray)

    print("done")

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

if __name__ == '__main__':
    main()
,

尝试一下:

import csv

testarray = ["Hello","John"]

with open('test.csv',newline='') as csvfile:
    writer= csv.writer(csvfile,delimiter=' ',quotechar='|',quoting=csv.QUOTE_MINIMAL)
    writer.writerow(testarray)

这是来自页面:CSV File Reading and Writing

值得一读,以了解它为什么起作用。

,

我将使用Pandas Dataframe构建数据框并将其保存为CSV。如果您希望列表中的元素位于单独的行中,请

import pandas as pd
df1 = pd.Dataframe(testarray)

如果要在单个行中包含列表的所有元素,请执行此操作

df1 = pd.DataFrame([testarray])

另存为

df1.to_csv("my_test.csv",index = False)

您可以根据需要在数据框中添加列名。

如果您的列表如下:

list_of_list = [['A',15],['B',30],['C',45],['D',22]] 

您可以简单地执行以下操作,并使用带有标签的列

df_again = pd.DataFrame(list_of_list,columns =['letter','number']) 
df_again.to_csv("new_one.csv",index = False)
本文链接:https://www.f2er.com/3045259.html

大家都在问