在Python中使用json模块的入门问题
问题描述
#coding:GBKimport jsondef getstoredname(): filename = ’username.json’ try:with open(filename) as f: username = json.load(f) except:return None else:return usernamedef getnewname(): username = input('What is your name? ') filename = ’username.json’ with open(filename,’a+’) as f:json.dump(username,f) return username def greetuser(): username = getstoredname() if username:print('Welcome back, ' + username + '!') else:username = getnewname()print ('We’ll remember you when you come back, ' + username + '!')greetuser()
这个问题应该怎么改代码?
问题解答
回答1:def greetuser(): username = getstoredname() if username and input('Is that your name: ' + username + ' (y/n)')=='y': print('Welcome back, ' + username + '!') else:username = getnewname()print ('We’ll remember you when you come back, ' + username + '!')
我回答過的問題: Python-QA
回答2:import json’’’如果以前存储了用户名,就加载它,并询问是否为该用户的用户名,否则,就提示用户输入用户名并存储它 。’’’filename = ’username.json’try:
with open(filename) as f_obj: username = json.load(f_obj) if input(’Is that your name: ’ + username +’?’ + ’ (y/n) n’)==’y’:print('Welcom back,%s!' %username) else:username = input(’What is your name?n’)with open(filename,’w’) as f_obj: json.dump(username,f_obj) print('We’ll remember you when you come back,%s!' % username)
except FileNotFoundError:
username = input(’What is your name?n’)with open(filename,’w’) as f_obj: json.dump(username,f_obj) print('We’ll remember you when you come back,%s!' % username)
相关文章:
1. redis sentinel怎么跑守护进程以及日志记录位置的?2. python 字符串匹配问题3. 请问PHPstudy中的数据库如何创建索引4. django - Nginx uwsgi 进程问题5. javascript - sublime快键键问题6. 使用git管理webpack的代码时多人怎么协作?一般托管哪些文件?7. html - angular项目中如何让外链网页在本项目中展示?8. Python异常退出时保存进度?9. 前端 - 这段代码一直生效不了,查半天因为 top: 0px; 分号后一个隐藏的东西,也不是占位符...删了就可以生效,这是什么情况。。10. 这是什么情况???

网公网安备