python 读空的json文件

读空的json文件,python2和python3 的错误提示是不一样的

python2:

ValueError: No JSON object could be decoded

python3:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

解决:

针对python2

import json
data ={"vf":"ff"}
'''
#写入
with open('tmp.json', 'w') as f:
    json.dump(data, f)
'''
try:
    with open('tmp.json', 'r') as f:
        k=json.load(f)
        print(k)
except ValueError:
  print(
"empty!")

针对python3

import json
data ={"vf":"ff"}
'''
#写入
with open('tmp.json', 'w') as f:
    json.dump(data, f)
'''
try:
    with open('tmp.json', 'r') as f:
        k=json.load(f)
        print(k)
except json.decoder.JSONDecodeError:
    print("empty!")

原文地址:https://www.cnblogs.com/sea-stream/p/10011699.html