用于序列化的两个模块
json:用于字符串和python数据类型间进行转换
pickle:用于python特有的类型和python的数据类型间进行转换
json模块提供了四个功能:dumps dump loads load
pickle模块提供了四个功能: dumps dump loads load
pickle实例:
1: import pickle2: data = {‘k1‘:123,‘k2‘:‘hello‘}3: # pickle.dumps将数据通过特殊的形式转换为只用python语音能识别的字符串4: p_str = pickle.dumps(data)5: print p_str6: ‘‘‘7: 打印结果:8: (dp09: S‘k2‘10: p111: S‘hello‘12: p213: sS‘k1‘14: p315: I12316: s.17: ‘‘‘18: # pickle.dump 将数据通过特殊的形式转换为只有python语音认识的字符串,并写入文件19: with open(‘E:/python/tmp/result.pk‘,‘w‘) as fp:20: pickle.dump(data,fp)
json实例
1: import json2: data = {‘k1‘:123,‘k2‘:‘hello‘}3: # json.dumps 将数据通过特殊的形式转换为所有程序语言都认识的字符串4: j_str = json.dumps(data)5: print j_str6: # 打印结果:{"k2": "hello", "k1": 123}7: # json.dump 将数据通过特殊的形式转换为所有语言都认识的字符串,并写入文件8: with open(‘E:/python/tmp/result.pk‘,‘w‘) as jp:9: json.dump(data,jp)
ConfigParser
1: #!/usr/bin/env python2: # -*- coding:utf-8 -*-3: # 用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。4: import ConfigParser5: config = ConfigParser.ConfigParser()6: config.read(‘goods.txt‘)7:8: # 获取模块的名称9: secs = config.sections()10: print secs11: # 结果:[‘section1‘, ‘section2‘]12: # 获取指定模块的key值13: options = config.options(‘section1‘)14: print options15: # 结果:[‘k1‘, ‘k2‘]16: # 获取指定模块下的items17: item_list = config.items(‘section1‘)18: print item_list19: # 结果:[(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘)]20: # 获取指定模块下的key的值21: val = config.get(‘section1‘,‘k2‘)22: print val
时间: 2024-10-14 17:38:29