在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 gitlab 如何git clone?2. javascript - JS設置Video視頻對象的currentTime時出現了問題,IE,Edge,火狐,都可以設置,反而chrom卻...3. python的bs4如何篩選出h1標簽中的內容4. javascript - 移動端H5頁面禁止縮放了,在瀏覽器上仍然可以縮放5. java - spring-data Jpa 不需要執行save 語句,Set字段就可以自動執行保存的方法?求解6. angular.js - 通過數據中children的個數自動生成能點擊展開的div7. android - 安卓做前端,PHP做后臺服務器 有什么需要注意的?8. css - 使用blur()濾鏡為什么有透明的效果9. docker-compose 為何找不到配置文件?10. 前端 - css3 3d效果問題
