用于序列化的两个模块
json:用于字符串和python数据类型间进行转换
pickle:用于python特有的类型和python的数据类型间进行转换
json模块提供了四个功能:dumps dump loads load
pickle模块提供了四个功能: dumps dump loads load
pickle实例:
1: import pickle
2: data = {'k1':123,'k2':'hello'}
3: # pickle.dumps将数据通过特殊的形式转换为只用python语音能识别的字符串
4: p_str = pickle.dumps(data)
5: print p_str
6: '''
7: 打印结果:
8: (dp0
9: S'k2'
10: p1
11: S'hello'
12: p2
13: sS'k1'
14: p3
15: I123
16: 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 json
2: data = {'k1':123,'k2':'hello'}
3: # json.dumps 将数据通过特殊的形式转换为所有程序语言都认识的字符串
4: j_str = json.dumps(data)
5: print j_str
6: # 打印结果:{"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 python
2: # -*- coding:utf-8 -*-
3: # 用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。
4: import ConfigParser
5: config = ConfigParser.ConfigParser()
6: config.read('goods.txt')
7:
8: # 获取模块的名称
9: secs = config.sections()
10: print secs
11: # 结果:['section1', 'section2']
12: # 获取指定模块的key值
13: options = config.options('section1')
14: print options
15: # 结果:['k1', 'k2']
16: # 获取指定模块下的items
17: item_list = config.items('section1')
18: print item_list
19: # 结果:[('k1', 'v1'), ('k2', 'v2')]
20: # 获取指定模块下的key的值
21: val = config.get('section1','k2')
22: print val