Python-json和异常
1.文件操作补充
1)打开不存在的文件
如果以读的方式打开不存在的文件会报错;
如果以写的方式打开不存在的文件不会报错;
# open('test.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
# open('test.txt', 'w')
f = open('test.txt', 'a+')
# f.read()
f.write('abc')
2)读写模式:+
使用方式:r+ / w+ / a+ - 读写操作
3)通过文件上下文打开文件
文件对象 = open()
文件对象.read()/文件对象.write()
文件对象.close()
with open() as 文件对象:
文件对象.read()/文件对象.write()
with open('test.txt', 'w') as f:
f.write('abc')
f.write('123')
2.登录注册系统
# 设置账号持久化的方案
import json
"""
1)已经注册过的所有账号和密码需要本地化
2)需要创建文件来保存需要本地化的数据:a.哪个文件 b.文件中的初始值是什么
user_info.txt
初始值:[]
有数据的数据:[{'user':xxx, 'pw':xxx}, {'user':xxx, 'pw':xxx}]
"""
def register():
"""注册"""
# 1.输入账号和密码
# username = input('请输入账号:')
while True:
username = input('请输入账号(3-6位):')
if not 3 <= len(username) <= 6:
print('账号格式错误!')
continue
break
# password = input('请输入密码:')
while True:
password = input('请输入密码(6-12位):')
if not 6 <= len(password) <= 12:
print('密码格式错误!')
continue
break
# 2.检测账号是否注册
# 1)获取已经注册的账号信息
f = open('files/user_info.txt', 'r', encoding='utf-8')
# all_user_info = eval(f.read())
all_user_info = json.loads(f.read())
# 2)判断输入的用户名是否是已经注册过得用户名
user_name = [x['user'] for x in all_user_info]
if username in user_name:
print('注册失败!该账号已经注册过!')
f.close()
return
# 3.没有注册的时候,注册账号
all_user_info.append({'user': username, 'pw': password})
f = open('files/user_info.txt', 'w', encoding='utf-8')
# f.write(str(all_user_info))
f.write(json.dumps(all_user_info))
print('注册成功')
f.close()
def login():
"""登录"""
# 1.输入账号和密码
# username = input('请输入账号:')
while True:
username = input('请输入账号(3-6位):')
if not 3 <= len(username) <= 6:
print('账号格式错误!')
continue
break
# password = input('请输入密码:')
while True:
password = input('请输入密码(6-12位):')
if not 6 <= len(password) <= 12:
print('密码格式错误!')
continue
break
# 2.验证账号密码是否正确
# 0)获取曾经之前已经注册过的所有账号信息
f = open('files/user_info.txt', encoding='utf-8')
# all_user_info = eval(f.read())
all_user_info = json.loads(f.read())
# 1)判断账号是否注册过
if username not in [x['user'] for x in all_user_info]:
print('登陆失败!该账号不存在')
return
# 2)判断密码是否正确
for x in all_user_info:
if x['user'] == username:
if x['pw'] == password:
print('登陆成功!')
else:
print('登录失败!密码错误!')
return
def main_page():
page = open('files/mainpage.txt', encoding='utf-8').read()
while True:
# 1.显示主界面
print(page)
# 2.给出选择
value = input('请选择(1~3):')
# 3.根据选择执行不同操作
if value == '1':
# print('登录')
login()
elif value == '2':
# print('注册')
register()
elif value == '3':
return
if __name__ == '__main__':
main_page()
3.json数据
1)什么是json
json是一种通用的数据格式。
2)json是一种什么样的数据格式(通用)
一个json有且只有一个数据;唯一的这个数据必须是json支持的类型的数据。
json支持的类型:
数字 - 包含所有的整数和小数,表示的时候直接写,例如:900, -12, 0.34, 3e4
字符串 - 用双引号引起来的数据(支持转义字符),例如:“abc”, “试试234”, “abc\n123”
布尔 - 只有true和false两个值,表示的时候直接写:true, false
空值 - null, 表示的时候直接写:null
数组 - 相当于Python中的列表,[元素1, 元素2,…], 例如:[100, 200, “abc”, “abc\n123”, false, [1, 2, 3]]
字典 - 相当于Python中的字典, 但是键只能是字符串,例如:{“name”: “小明”, “age”: 18}
3)python数据和json数据之间的相互转换
python提供一个json模块,这个模块中有两个函数专门用来支持json和python的相互转换
4)json转python (loads函数)
json --> python
数字 int/float
字符串 str,可能会将双引号变成单引号
布尔值 bool, true -> True; false -> False
空值 null -> None
数组 list
字典 dict
loads(json格式的字符串) - 将json格式的字符串转换成对应的python数据
json格式的字符串: 字符串的内容是一个合法的json数据(去掉字符串外面的引号,剩下的部分是一个合法的json数据)
5)python转json(dumps函数)
python —> json
int/float 数字
str 字符串;单引号会变成双引号
bool True -> true; False -> false
list/tuple 数组
dict 字典; 键会转换成字符串
None null
dumps(python数据) - 将python数据转换对应的json格式的字符串
import json
result = json.loads('"abc"')
print(result) # 'abc'
result = json.loads('[120, "abc", true, null]')
print(result, type(result)) # [120, 'abc', True, None] <class 'list'>
result = json.dumps([100, 'abc', True, None])
print(result, type(result)) # [100, "abc", true, null] <class 'str'>
# '[100, "abc", true, null]'
result = json.dumps({10: 200, False: 'abc', 'a': True})
print(result, type(result)) # '{"10": 200, "false": "abc", "a": true}'
4.异常捕获
1)异常
程序报错就叫程序异常
如果程序出现异常会终止程序的执行。
2)捕获异常
异常捕获就是让程序中指定的代码段在出现异常后不终止程序的执行,让程序接着执行。
什么时候需要捕获异常:明知道某个位置可能会出现异常,但是不是因为代码不符合语法造成,而是使用者使用不当造成,
但是又不希望这个地方出现异常的时候终止程序的执行。
3)怎么捕获
结构一:捕获任意异常
try:
需要捕获异常的代码
except:
捕获到异常后会执行的代码
finally:
代码段(写遗书)
结构二:捕获指定类型的异常
try:
需要捕获异常的代码
except 异常类型:
捕获到异常后会执行的代码
finally:
代码段
结构三:同时捕获多种异常
try:
需要捕获异常的代码
except (异常类型1, 异常类型2,…):
捕获到异常后会执行的代码
finally:
代码段
结构四:同时捕获多种异常
try:
需要捕获异常的代码
except 异常类型1:
处理方法1
except 异常类型2:
处理方法2
…
finally:
代码段
4)finally
finally后面的代码不管前面是否出现异常,也不管异常是否被捕获都会执行
try:
age = int(input('请输入年龄:'))
if age >= 18:
print('成年')
else:
print('未成年')
except:
print('年龄输入有误! 必须是整数')
pass
try:
print('hello')
# print(10 + 'a')
# print([10][9])
except TypeError:
print('类型错误')
finally:
print('写遗书')
print('=====')
5.抛出异常 - 主动让程序崩溃
raise 异常类型
class AgeError(Exception):
def __str__(self):
return '年龄值错误,年龄的有效范围是1 ~ 200'
age = int(input('请输入年龄:'))
if age <= 0 or age > 200:
raise AgeError
print('--------')
raise KeyError
print('++++++++')