序列化json
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:woshinidaye 4 #正常读取文件的时候,文档使用字符串的形式写进去的。 5 # a = {'name':'woshinidaye','age':22} 6 # with open('test','w+',encoding='utf-8') as f : #序列化 7 # # f.write(a) #直接写入会报错,因为a是字典, 8 # f.write(str(a)) 9 # 10 # with open('test','r+',encoding='utf-8' ) as f : #反序列化 11 # # c= f.read() #直接这样执行会报错,TypeError: string indices must be integers 12 # d = eval(f.read()) # The source may be a string representing a Python expression 13 # #or a code object as returned by compile(). 14 # # print(c['age']) 15 # print(d['age']) #这样就行,不过eval不是最推荐的办法,推荐使用json 16 17 ''' 18 import json 19 a = {'name':'woshinidaye','age':22} 20 with open('test','w+',encoding='utf-8') as f : 21 f.write(json.dumps(a)) #序列化 22 23 with open('test','r+',encoding='utf-8') as f : #反序列化 24 test = json.loads(f.read()) 25 print(test) 26 ''' 27 #json只能用于简单的字体序列化,因为json会用到各种语言中,json此时作为序列化的中间商 28 29 ''' 30 import pickle #可以对函数序列化,只能在python里面用,其他语言无法识别。 31 def b(): 32 print('b') 33 a = {'name':'woshinidaye','age':22,'func':b} 34 with open('test','wb') as f : 35 f.write(pickle.dumps(a)) #序列化 36 #f.write(pickle.dumps(a)) = pickle.dump(a,f) 37 with open('test','rb') as f : #反序列化 38 test = pickle.loads(f.read()) 39 #test = pickle.load(f) 40 print(test) #{'name': 'woshinidaye', 'age': 22, 'func': <function b at 0x00000219CFB4AC10>} 41 print('====>',test['func']()) 42 test['func']() 43 '''
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
2020-11-05 抽空学学KVM(八):虚拟机的网络---Bridge模式