在Python中将列表编写为csv

时间:2017-03-17 20:44:39

标签: python list csv

我在Phyton中有一个类似于:

的列表
mylist ='thank you i love you ', 'my mom my biggest supporter’,’ my life line my best friend was a single parent worked 2 jobs to support us im so blessed to have her ’,’ as a mom and now shes my babys nonna happy mothers day mommy i love you', 'me and my mom love her to pieces'.

我想保存输出应该如下的csv或txt文件:

1. thank you  i love you
2. my mom my biggest supporter
3. my life line my best friend was a single parent worked 2 jobs to support us im so blessed to have her
4. as a mom and now shes my babys nonna happy mothers day mommy i love you
5. me and my mom love her to pieces 

我一直在尝试:

for item in mylist:
    mylist.write("%s/n" % item)

但我明白了:

AttributeError: 'list' object has no attribute 'write'

我该怎么办?

提前致谢!

4 个答案:

答案 0 :(得分:2)

这看起来似乎微不足道,但我没有找到任何重复的回答那个特别简单的问题(在几分钟内找到它们!)所以这是我的建议:

with open("output.txt","w") as f:
    for i,item in enumerate(mylist,1):
        f.write("{}. {}\n".format(i,item))
  • mylist是一个输入,你不能write进入它。您必须打开一个文件对象并对mylist个元素进行迭代(使用enumerate将其与索引从1开始压缩。)
  • 您还为换行符写了/n,该字符应为\n(远离os.linesep,因为它会在Windows上添加\r两次

答案 1 :(得分:0)

首先,您需要稍微更改列表,因为有时您使用的是而不是'。 这是更正后的清单:

myList = 'thank you i love you ', 'my mom my biggest supporter', ' my life line my best friend was a single parent worked 2 jobs to support us im so blessed to have her ', ' as a mom and now shes my babys nonna happy mothers day mommy i love you', 'me and my mom love her to pieces'

其次,您需要将值写入文件对象,而不是列表对象。

file_object = open('the_output_file_name.txt', 'w')    #creates a file

for item in myList:
    file_object.write("%s\n" % item)    #writes the item to the file

file_object.close()

如果你希望输出有像你的例子中的行号,你可以使用它来迭代列表和一个等于列表长度的数字列表:

file_object = open('the_output_file_name.txt', 'w')    #creates a file

for item, number in zip(myList, range(len(myList))):    #loop over myList and a range()
    file_object.write("%d. %s\n" % (number + 1, item))    #writes the item to the file

file_object.close()

答案 2 :(得分:0)

mylist是一个列表对象,它没有写入功能。 因此,你得到了一个AttributeError。

您需要打开一个文件来写一些数据,这是我的解决方案:

with open('output.txt', 'w') as f:
    [f.write("%d. %s\n" % (i,v)) for i,v in enumerate(mylist, 1)]   

答案 3 :(得分:0)

你应该file 而不是一个list对象,单引号错误,尝试以下方法:

open('text.txt', 'a').write("\n".join(mylist))