''' 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}")
python文件处理之JSON
最新推荐文章于 2024-07-08 00:01:13 发布