簡體   English   中英

Python:逐行將列表寫入文件

[英]Python: Write list to file, line by line

我想每次從新行將以下list寫入文件。

bill_List = [total_price, type_of_menu, type_of_service, amount_of_customers, discount]

我嘗試使用此代碼,但它只會覆蓋文本文件。 有人可以幫我嗎? 我的錯誤在哪里?

# attempt #1
f = open("Bills.txt", "w")
f.write("\n".join(map(lambda x: str(x), bill_List)))
f.close()


# attempt #2
# Open a file in write mode
f = open('Bills.txt', 'w')
for item in bill_List:
f.write("%s\n" % item)
# Close opend file
f.close()

# attempt #3

with open('Bills.txt', 'w') as f:
for s in bill_List:
    f.write(s + '\n')

with open('Bills.txt', 'r') as f:
bill_List = [line.rstrip('\n') for line in f]

# attempt #4
with open('Bills.txt', 'w') as out_file:
out_file.write('\n'.join(
    bill_List)) 

我認為您正在尋找'a'而不是'w'作為緩沖參數:

with open('Bills.txt', 'a') as out_file:
    [...]

參見https://docs.python.org/2/library/functions.html?highlight=open#open

暫無
暫無

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

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