编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储在文件中,如果文件中存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储在文件中,运行这个程序两次。
代码:
import json
filename = 'favorite.json'
try:
with open(filename) as f_obj:
num = json.load(f_obj)
except FileNotFoundError:
number = input('Your favorite number is:')
with open(filename,'w') as f_obj:
json.dump(number,f_obj)
else:
print('I know your favorite number is '+ num)
运行两次的结果为:
![](https://i-blog.csdnimg.cn/blog_migrate/d14bb6f029f159f89c63ac88f9424899.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e54520853764f8def11254e5880287f3.png)