CoreVisional
CoreVisional

Reputation: 99

Nesting 'r' after opening a file in write mode

so I had an exercise asking to write to a file (using newlines) and then open it in reading mode. I did exactly that and the console outputs the right result. What happened was that I tried to do it within the 'w' mode code block and the console outputs nothing.

For example:

with open('test.txt', 'w') as wf:

    nicknames = ["Big Tuna", "Prison Mike", "Booster Seat"]

    wf.write('\n'.join(nicknames))

    with open('test.txt', 'r') as rf:

        print(rf.read())

I understand that the program only closes the file after the with statement, but I need clarification on my understanding of what's happening here.

So, what I understood so far is that the program first creates the test.txt file (test.txt did not exist in my file path) and then proceeds to convert and write the given contents into the test.txt file. After that, the nested with tries to open a file named test.txt in reading mode, but the console will not output anything because the program is trying to open a file that is already opened, that's why it cannot read into an already opened file.

Please correct me if I'm misunderstood the above because I am unsure whether or not I've understood it correctly, thank you.

Upvotes: 1

Views: 80

Answers (1)

Kirk Strauser
Kirk Strauser

Reputation: 30933

That’s not what’s happening. Unix systems, at least, will happily let you open a file multiple times.

However, Python’s IO is buffered by default. You need to flush the data you’ve written out to the file before you can read the data from it. See https://docs.python.org/3/library/io.html#io.IOBase.flush for more information about this. (Summary: put wf.flush() after the wf.write(…) call and before attempting to read from it.

Upvotes: 2

Related Questions