简体   繁体   中英

Python: Write list to file, line by line

I want to write the following list to file, each time from new line.

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

I tried to use this code but it just overwrites the text file. Could somebody help me? Where is my mistake?

# 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)) 

I think you are looking for 'a' instead of 'w' for the buffering parameter:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM