【发布时间】:2017-05-21 01:58:36
【问题描述】:
我想将以下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))
【问题讨论】:
-
为什么要将代码格式化为字符串?
-
@famargar,我也试过了,但
for item in thelist: thefile.write("%s\n" % item)也会覆盖文件,否则我做错了什么( -
@AndrewJaffe,是的,没有意义,我改变格式