在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. java - 3个dao的数据根据请求参数选择一个映射到一个url上,怎么写比较好?2. html5 - 百度Ueditor代码高亮和代码段滚动条冲突是怎么回事?3. docker 17.03 怎么配置 registry mirror ?4. javascript - 关于一段 for 循环代码执行顺序的问题5. javascript - 读取页面源码,页面中所有的换行都被当成<br/>读取出来 了,,求解应该怎么让它被正确的解析6. docker网络端口映射,没有方便点的操作方法么?7. javascript - 静态页面引公共头尾文件,js怎么写吖?8. javascript - vue 数据更新了。但是dom没有更新,,,,,如图9. javascript - JS中如何实现 DIV内部和鼠标的距离10. docker绑定了nginx端口 外部访问不到