11

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?

3
  • 1
    Opening a file in "w" mode removes all the data in the file if it exists. Commented Mar 5, 2016 at 18:37
  • Try: the_file = open("somefile.txt", "wb", buffering=False). Commented Mar 5, 2016 at 18:57
  • Lets go back to your original write. Your writes are buffered until you've either written a block of data or you close the file. So you may not see the data on disk yet. Commented Mar 5, 2016 at 19:03

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess the part that's confusing for me is that I'm passing this file object around to different functions so I'm declaring it as a variable. If I create the file w/ var = open("file","w") then how can I append to that variable later?
@O.rka: About the buffering in the file: the with statement creates a context manager that takes care of calling the_file.close() at the end and thereby flushing the file to disk. If you quit your Jupyter-process, the files should appear.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.