3

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)) 
lorenzog
  • 3,037
  • 3
  • 26
  • 47
Bogdan Skripnik
  • 85
  • 3
  • 14

1 Answers1

1

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

lorenzog
  • 3,037
  • 3
  • 26
  • 47
  • 1
    No problem. While you are at it, consider also `writelines()`: https://docs.python.org/2/library/stdtypes.html?highlight=writelines#file.writelines (I am not sure it applies to your case) – lorenzog Jan 06 '17 at 10:57