簡體   English   中英

如何將 3D 列表寫入帶有空格的文本文件並刪除逗號和語音標記

[英]How can I write a 3D list to a text file with spaces and have the commas and speech marks removed

這是我使用的代碼:

with open('database.txt', 'w') as f:
    for item in my_list:
        f.write('%s\n' % item)
    f.close()

它有效,但我希望 3D 列表中的元素間隔開,並刪除逗號和語音標記,以便文本文件看起來更美觀。

目前,在文本中它看起來像這樣:

['a','b','c']

['d','e','f']

但我希望它看起來像這樣:

ab c

定義

使用join function。

with open('database.txt', 'w') as f:
    for item in my_list:
        f.write('%s\n' % ' '.join(item))

這里也不需要f.close() 當您離開with open塊時,文件會自動關閉。

您應該將列表轉換為字符串:

with open('database.txt', 'w') as f:
    for item in my_list:
        f.write('%s\n' % ' '.join(item))
    f.close()

暫無
暫無

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

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