簡體   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