已解决
【Python基础】S01E12 json 文件简单处理
来自网友在路上 151851提问 提问时间:2023-09-29 14:43:09阅读次数: 51
最佳答案 问答题库518位专家为你答疑解惑
S01E12 文件(下)
- json 数据基本处理
- 读取 json 数据
- 写入 json 数据
- 一个应用场景
本文将主要围绕 json 格式字符串的读取与存储做介绍。关于普通 txt 文件的读写,请见:【S01E11 文件(上)】:https://xu-hongduo.blog.csdn.net/article/details/133377596
json 数据基本处理
读取 json 数据
我们使用 json.loads()
来读取 json 文件 information.json
information.json
{"name": "John","age": 30,"city": "New York"
}
read_json.py
import jsonwith open('information.json', 'r') as file:# 使用 json.load() 函数加载JSON数据data = json.load(file)print(data)>>> {'name': 'John', 'age': 30, 'city': 'New York'}
写入 json 数据
我们使用 json.dumps()
来存储 json 数据到文件 output.json
中
import jsondata_to_write = {'name': 'John','age': 30,'city': 'New York'
}with open('output.json', 'w') as file:# 使用json.dump()函数将数据写入JSON文件json.dump(data_to_write, file)
一个应用场景
用户输入名称。如果记录用户名的文件 username.json
中存在该用户,则输出 Welcome, {username}
。如果没有找到,则自动将用户名记录到 username.json
中。
import json
import osdef check_user(username):try:with open('username.json', 'r') as file:existing_users = json.load(file)if username in existing_users:return Trueelse:return Falseexcept (FileNotFoundError, json.decoder.JSONDecodeError):return Falsedef main():username = input("请输入用户名: ")if check_user(username):print(f"Welcome, {username}")else:print(f"用户 {username} 不存在,将其录入到username.json文件中")existing_users = []# 如果文件存在,尝试读取已有的用户if os.path.exists('username.json'):try:with open('username.json', 'r') as file:existing_users = json.load(file)except json.decoder.JSONDecodeError:passexisting_users.append(username)with open('username.json', 'w') as file:json.dump(existing_users, file)if __name__ == "__main__":main()
上述代码中使用了 try-except
代码块,该代码块的作用是不确定是否会发生错误,但是发生错误时,程序不会因为错误直接退出运行,而是转而运行 except 中内容并继续向下执行。
有关于 try-except 的内容,请看下篇博文:【S01E13 Python异常】
祝大家、国家2023年中秋节、国庆节双节快乐!
北京海淀西三旗
2023.9.28
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"【Python基础】S01E12 json 文件简单处理":http://eshow365.cn/6-15432-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 实验室没人导该怎么办
- 下一篇: PHP 变动:用于创建常量数组的 define() 与 const