簡體   English   中英

python寫入列表到文件

[英]python write list to file

這篇文章中,我一直在使用以下代碼將列表/數組寫入文件:

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % item)

其中hostnameIP是:

[['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]

在文件中,我得到輸出:

['localhost', '::1']
['localhost', '::1']
['localhost', '::1']

當我需要說的時候

localhost, ::1
localhost, ::1
localhost, ::1

最好的方法是什么?

采用:

with open ("newhosts.txt", "w") as thefile:
    for item in hostnameIP:
        thefile.write("%s\n" % ", ".join(item))

這樣,項目的每個部分都將印有“,”作為分隔符。

但是如果你想讓代碼更短,你也可以用換行符加入每個項目:

with open ("newhosts.txt", "w") as thefile:
    thefile.write("\n".join(map(", ".join, hostnameIP)))
with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s, %s\n" % (item[0], item[1]))

我會使用csv模塊簡單地在列表列表中調用writerow:

import csv
lines = [['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]
with open ("newhosts.txt",'w') as f:
    wr = csv.writer(f)
    wr.writerows(lines)

輸出:

localhost,::1
localhost,::1
localhost,::1

從我可以看到你有一個列表作為元素列表。 這就是為什么你得到你得到的結果。 嘗試以下代碼(請參閱第三行的小改動),您將獲得想要的結果。

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % ', '.join(item))

您當前正在將列表的字符串表示打印到文件中。 由於您只對列表項感興趣,因此可以使用str.format和argument str.format來提取它們:

thefile.write("{}, {}\n".format(*item))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM