Using “with open() as file” method, how to write more than once? [duplicate]

The w flag means “open for writing and truncate the file”; you’d probably want to open the file with the a flag which means “open the file for appending”.

Also, it seems that you’re using Python 2. You shouldn’t be using the b flag, except in case when you’re writing binary as opposed to plain text content. In Python 3 your code would produce an error.

Thus:

with open('somefile.txt', 'a') as the_file:
    the_file.write("durin's day\n")

with open('somefile.txt', 'a') as the_file:
    the_file.write("legolas\n")

As for the input not showing in the file using the filehandle = open('file', 'w'), it is because the file output is buffered – only a bigger chunk is written at a time. To ensure that the file is flushed at the end of a cell, you can use filehandle.flush() as the last statement.

Leave a Comment