我正在用 Python 编写代码,需要通过 RFID 标签注册用户并将该记录写入文件。
我设法编写了一个运行良好的函数:
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)
但我想尽可能优化代码,减少行数。因此,我决定使用它,w+因为它应该能够同时读取和写入文件。
这是“优化”的代码:
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)
“优化”代码不起作用,它给出了这个错误:
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
将保存记录的文件:
{"recordsList": []}
有人能告诉我为什么会这样吗?
慕妹3242003
12345678_0001
相关分类