import json
def remember_me():
file_name = 'User.json'
try:
with open(file_name) as r_obj:
username = json.load(r_obj)
# ①可以用except Error_1 or Error_2;②当json文件存在,内容空白时,会出现json.JSONDecodeError
except json.JSONDecodeError or FileNotFoundError:
username = input('Please key in your name:')
with open(file_name, 'w') as object_1: # 与这行的object_1一致
json.dump(username,
object_1) # 像这行,json.dump(contents to write, object_file) 这个object_file一定是和上面的object_1一致的
else:
print('We have remembered you,' + username + '!')
with open(file_name) as object_2: # 同理,json括号中的内容,一定是和 as object_name中的object_name一致。
contents = json.load(object_2) #
print('Nice to see you again,' + contents + '!')
if __name__ == '__main__':
remember_me()
except、json用法
最新推荐文章于 2024-09-05 16:15:02 发布