我在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'
我该怎么办?
提前致谢!
答案 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))