python的机器人设计之账号管理:机器人账号的class定义和json文件格式存储

avatar

开发机器人最方便的工具是 python,既能跨平台开发,而且语法灵活,实现方便.

屏幕快照 2020-01-31 下午1.49.54.png
为了方便单一功能的机器人运行,通常不会接口数据库,因此比较常见的是用文件做一些数据的交互和存储.

数据无论通过文件交互,还是通过网络交互,json格式的 跨平台、跨语言支持,无疑是最好的选择.

这里就示范一下python bot对 json 文件的存取操作(users_json.py).

import json
# import file

users_file = 'users.json'

# 初始化信息:字符串转成字典
bot_accounts = '''
{
        "users": [
                {
                        "id": 1,
                        "name": "user12",
                        "grade": "天蝎座",
                        "phone": "13488709999",
                        "tokens": 10401
                },
                {
                        "id": 2,
                        "name": "user35",
                        "grade": "双鱼座",
                        "phone": "18612511888",
                        "tokens": 100
                }
        ]
}
'''
user_dicts = json.loads(bot_accounts)  # 加载初始化json格式信息
print('init.user_dicts:', user_dicts)

try:
    uf = open(users_file, 'r', encoding='utf-8')  # 支持中文
    user_dicts = json.load(uf)  # 读取json文件中的字符串信息,覆盖初始化json格式信息
    print('old.user_dicts:', user_dicts)
    uf.close()
except IOError:
    uf = open(users_file, 'w', encoding='utf-8')
    # user_dicts = {'users': []}  # 初始化信息

with open(users_file, 'w', encoding='utf-8') as f:
    # indent为缩进,中文默认使用的ascii编码,中文需要ensure_ascii=False
    json.dump(user_dicts, f, indent=4, ensure_ascii=False)

with open(users_file, 'r', encoding='utf-8') as f:
    # 直接用load()传入文件对象,将文件中字符串内容转为json字典
    user_dict2 = json.load(f)
    print('old.user_dict2:', user_dict2)
    user_dict2['users'].append({
        "id": 3,
        "name": "user58",
        "grade": "双子座",
        "phone": "718612511777",
        "tokens": 700
    })
    print('new.user_dict2:', user_dict2)
with open(users_file, 'w', encoding='utf-8') as f:
    # 用dump()传入字典和文件对象,将json字典转为字符串,存入文件
    json.dump(user_dict2, f, indent=4, ensure_ascii=False)

执行命令:python users_json.py

执行结果,符合预期:
屏幕快照 2020-01-31 下午1.47.27.png



0
0
0.000
1 comments
avatar

According to the Bible, Why was Jesus Christ baptized despite being sinless? (Part 2 of 2)

(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)



Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to Thank you, our beloved friend.
Check our Discord Chat
Join our Official Community: https://beta.steemit.com/trending/hive-182074

0
0
0.000