#json操作
import json
data = {
'username':'admin',
'password':'admin',
'age':20,
'sex':'男',
'email':'434754018@qq.com'
}
#字典转字符串
with open('jsonToStr.txt', 'w', encoding='utf-8') as f:
data = json.dumps(data)
f.write(data)
#修改文本内容
with open('jsonToStr.txt', 'r+') as f:
data2 = json.loads(f.read()) #字符串转字典
data2['sex']='male'
f.seek(0) #把文件指针移到到头部
print(f.tell())
f.write(json.dumps(data2))
#读取文本内容
with open('jsonToStr.txt', mode='r', encoding='utf-8') as f:
data= f.read()
#打印数据类型
print(type(data))
print(data)
#模拟登陆
userData ={
'admin':{
'pwd':'admin',
'lock':0
},
'merry':{
'pwd':'123',
'lock':1
},
'adc':{
'pwd':'123',
'lock':0
}
}
#将数据写入json文件 字符串
with open('account.json', mode='w', encoding='utf-8') as f:
data3 = json.dumps(userData)
f.write(data3)
print(type(data3))
#读取文件
with open('account.json', mode='r+', encoding='utf-8') as f:
#读取文件内容
data4 = json.loads(f.read())
count=0
while 1:
username = input('请输入你的用户名:')
if username == 'q':
exit()
if username not in data4:
print('你输入的用户不存在!')
continue
if username in data4:
if data4[username]['lock'] == 1:
print('你的账户被锁定,无法登陆!')
exit()
while 1:
count += 1
if count > 2:
data4[username]['lock'] =1
print(data4)
f.seek(0)
f.write(json.dumps(data4))
print('你的账户被锁定!')
exit()
print('这是你 %d 次 尝试!' % count)
password = input('请输入你的密码:')
if data4[username]['pwd'] == password:
print('欢迎 %s 登陆!' % username)
exit()
elif password == 'q':
exit()
else:
print('密码错误!')
continue