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:

def register_user(self, rfid):

    with open(self._RECORDS_FILE_PATH, 'r') as infile:
        recordsData = json.load(infile)

    with open(self._RECORDS_FILE_PATH, 'w+') as outfile:
        newRecord = {
            "timestamp": int(round(time.time() * 1000)),
            "rfid": rfid
        }
        recordsData["recordsList"].insert(0, newRecord)
        json.dump(recordsData, outfile)

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:

def register_user(self, rfid):

    with open(self._RECORDS_FILE_PATH, 'w+') as file:
        recordsData = json.load(file)
        newRecord = {
            "timestamp": int(round(time.time() * 1000)),
            "rfid": rfid
        }
        recordsData["recordsList"].insert(0, newRecord)
        json.dump(recordsData, file)

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

Traceback (most recent call last):
  File "/home/pi/accessControl/accessControlClasses/userInfoApi.py", line 57, in register_user_offline
    recordsData = json.load(outfile)
  File "/usr/lib/python2.7/json/__init__.py", line 291, in load
    **kw)
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

The file in which records will be saved:

{"recordsList": []}

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