python json 文件读写

import json

test_dict = {'bigberg':7600,'iPhone':6300,'Bike':800,'shirt':300}

print(test_dict)
print(type(test_dict))#字典

#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)

print(json_str)
print(type(json_str))#字符串

with open("record.json","w") as f:
    json.dump(test_dict,f)
    print("写入文件完成...")


with open("record.json",'r') as load_f:
    load_dict = json.load(load_f)
    print(load_dict)
    print(type(load_dict))#字典
    print("读取文件完成...")


#修改文件内容
load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}]
print(load_dict)

with open("record.json","w") as dump_f:
    json.dump(load_dict,dump_f)

猜你喜欢

转载自www.cnblogs.com/sea-stream/p/9847422.html