python-Json文件

一、Json文件读取

1. 创建file格式文件:

2. 文件内输入内容

键值对表示,对象由逗号分隔

{"age": 14, "sex": "male", "address": "123"}

3. 新建py文件(名字不能叫json),代码如下:

import json  #导入模块
file = open("a.json", "r", encoding="utf-8") # 打开刚写入的文件+指定字符集
data = json.load(file) # json内容转化为字典传入data变量
file.close()
print(data) # 输出变量
#遍历字典
for n in data:
    print(n,data[n])

结果(显示为字典形式):

遍历字典后;

二、写Json文件

import json
dict1 = {"age": 14, "sex": "male", "address": "123"} # 创建字典
file = open("a.json", "w", encoding="utf-8") # 用只写方式
json.dump(dict1, file, ensure_ascii=False) # dump写入,ensure_ascii=False中文不转义
# file.close()
# #print(data)

三、修改文件

思路:先读取a.json中的内容,转换为字典更改值,在回写到文件中

import json
file = open("a.json", "r", encoding="utf-8") # 打开a.json文件
# dict1 = json.load(file) #读取文件并转换为字典
# file.close()
# dict1["age"] = 22 # 修改内容
# file = open("a.json", "w", encoding="utf-8") # 打开文件
# json.dump(dict1, file, ensure_ascii=False) # 写入新内容
# file.close()

猜你喜欢

转载自blog.csdn.net/Kiraxqc/article/details/125622291