繁体   English   中英

在Python中以csv形式编写列表

[英]writing a list as csv in Python

我在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'

我应该如何进行?

提前致谢!

这看似微不足道,但是我没有找到任何重复的答案来回答这个特定的简单问题(花了几分钟寻找它们!),所以这是我的建议:

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两次)

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

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()

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

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

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

您应该写入 file 而不是 list对象,而且单引号错误 ,请尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM