在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. docker - 如何修改运行中容器的配置2. angular.js使用$resource服务把数据存入mongodb的问题。3. html5 - 用h5本地存储是否安全?4. java - 为什么第一个线程已经释放了锁,第二个线程却不行?5. css3 - css将div定位到图片上的固定位置6. docker 下面创建的IMAGE 他们的 ID 一样?这个是怎么回事????7. 我在centos容器里安装docker,也就是在容器里安装容器,报错了?8. 在应用配置文件 app.php 中找不到’route_check_cache’配置项9. javascript - 编程,算法的问题10. mysql - 我的myeclipse一直连显示数据库连接失败,不知道为什么

网公网安备