如何将列表转换为csv中的列?

2024-10-04 09:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我有一个填充列表

list =[a, b, c, d]

我想将列表的内容转换为csvfile,并使列表的所有元素都成为一列。这是我的当前代码:

with open('twitter3.csv', 'w+') as csvfile:
    writer = csv.writer(csvfile, dialect='excel')
    writer.writerow(list)

输出的csv文件包含列表的元素,但正如方法所暗示的,它已将所有内容写入第一行。你知道吗

我试过创建for循环来编写每个element + \n,但是writerow方法有一个问题(在每个字母后面加逗号),而且csvwriter没有writecolumn方法。你知道吗


Tags: csvcsvfile方法代码元素内容列表as
3条回答

您可以将列表中的元素连接到一个字符串中,并使用新行字符'\n\r'作为分隔符,然后将整个字符串写入文件。你知道吗

例如:

my_list = [a, b, c, d]

with open("twitter3.csv", "w+") as csvfile:
    to_write = "\n\r".join(my_list)
    csvfile.write(to_write)

(也是'\n'工程)

要执行此任务,我将使用^{}包,如下所示:

import pandas as pd
l=["a","b","c","d"]
df=pd.DataFrame(l,index=False,header=False)
df.to_csv("twitter3.csv")

pandas阅读csv文件甚至处理Excel文件也很好。你知道吗

这是我能想到的最简单的方法:

import csv

my_list = ['a', 'b', 'c', 'd']

with open('twitter3.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='excel')
    writer.writerows(tuple(item) for item in my_list)

注意,我将list变量的名称更改为my_list,这样它就不会与内置的list类冲突。你知道吗

相关问题 更多 >