python文件处理之JSON

'''
json文件处理
'''
# 导入json工具包
import json

'''
读取json文件中的内容,并将其转化为字典
'''
# 打开json文件
with open("config/infos.json", encoding= "utf-8") as json_file:
    # 读取json内容并使用loads将 字符串 转换为 字典,赋值给变量json_dict
    # load: 把文件打开,并把字符串变换为数据类型
    json_dict = json.load(json_file)
    print(f"{type(json_dict)}:{json_dict}")
    # for key,value in enumerate(json_dict):
    #     print(f"{key}>>>{value}")
    for key,value in json_dict.items():
        print(f"{key}>>>{value}")

'''
将字典转换成字符串
'''
# 使用dumps:将python中的 字典 转换为 字符串
str_json_dict = json.dumps(json_dict, ensure_ascii=False)
print(f"{type(str_json_dict)}:{str_json_dict}")

'''
将数据写入json文件中
'''
# dump: 将数据写入json文件中,文件不存在则创建一个新文件写入,存在则在文件尾追加内容
with open("config/info.json", "a+") as dump_file:
    json.dump(json_dict, dump_file)
    # write的传参必须是一个字符串
    dump_file.write(str_json_dict)
    print("文件加载完成")

'''
将字符串转化成字典
'''
with open("config/info.txt", encoding= "utf-8") as txt_file:
    # loads将字符串转化为字典,然后使用字典的方法对文件内容进行处理
    txt_str = txt_file.read()
    print(f"{type(txt_str)}:{txt_str}")
    str_json = json.loads(txt_str)
    print(f"{type(str_json)}:{str_json}")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值