Sunday, November 10, 2019

python - Using "with open() as file" method, how to write more than once?




Usually to write a file, I would do the following:



the_file = open("somefile.txt","wb")
the_file.write("telperion")


but for some reason, iPython (Jupyter) is NOT writing the files. It's pretty weird, but the only way I could get it to work is if I write it this way:




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

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


But obviously it's going to recreate the file object and rewrite it.




Why does the code in the first block not work? How could I make the second block work?


Answer



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.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...