Python:逐行将列表写入文件

时间:2017-01-06 10:15:22

标签: python list file

我想每次从新行写下以下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)) 

1 个答案:

答案 0 :(得分:1)

我认为你正在为缓冲参数寻找'a'而不是'w':

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

请参阅https://docs.python.org/2/library/functions.html?highlight=open#open

相关问题