繁体   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