Skip to content
Advertisement

Why does changing to `w+` mode for simultaneous reading from and writing to a file cause the read to fail?

I am writing code in Python which needs to register a user by RFID tag and write that record to a file.

I managed to write a function which works perfectly fine:

JavaScript

But I would like to optimise the code as much as possible and reduce the number of lines. Because of that, I decided to use w+ because it should enable reading from and writing to the file simultaneously.

This is the “optimised” code:

JavaScript

The “optimised” code is not working and it is giving this error:

JavaScript

The file in which records will be saved:

JavaScript

Can someone tell me why is this happening?

Advertisement

Answer

Opening the file in w+ mode truncates it, so there is nothing to read once you try to do it. This mode is meant to allow you to go back and read what you wrote after opening the file.

As you will have to read the file, you need to open it in r mode. As you want to replace the whole content later, you will have to truncate it and open it in w mode. So, stay with your original version!

Advertisement