首页 > 编程语言 > 详细

Python 笔记:10 文件的写入与读取(JSON)

时间:2019-09-18 22:43:33      阅读:87      评论:0      收藏:0      [点我收藏+]

JSON:是一种轻量级的数据交换格式。Python中包含了json模块来对JSON进行编解码。
功能:主要应用的两个函数为:
    json.dumps(): 对数据进行编码。
    json.loads(): 对数据进行解码。
    在json的编解码过程中,python的原始类型会与json类型进行相互转换。

格式:

import json
data={
‘pluno‘:‘131001‘,
‘pluname‘:‘egg‘,
‘price‘:‘4.98‘,
‘qty‘:‘100‘
}
filename=‘txt_files/data.json‘
#open()函数中,第一个参数(filename),是要把数据保存到txt_files目录下,新建文件data.json格式
with open(filename,‘w‘) as file1:
# json.dump(),参数data,是要保存的数据(上面的data字典),file1,表示要保存到的文件(data.json)
json.dump(data,file1)
file1.write(‘\n‘)

#这里好像有点问题,json.load()只能读取1行,读取多行就报错:
with open(filename,‘r‘) as file2:    
f1=json.load(file2)
print(f1)
print(type(f1))
结果:{‘pluno‘: ‘131001‘, ‘pluname‘: ‘egg‘, ‘price‘: ‘4.98‘, ‘qty‘: ‘100‘}
  <class ‘dict‘>

 

Python 笔记:10 文件的写入与读取(JSON)

原文:https://www.cnblogs.com/wssking/p/11545516.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!