文件的保存

这是我个人总结,或好或坏,能用就行:

第一种:调用json

 

将Python内置类型序列化为json对象后写入文件

# json_dump.py

import json

listStr = [{"city": "北京"}, {"name": "大刘"}]
json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)

dictStr = {"city": "北京", "name": "大刘"}
json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)

读取文件中json形式的字符串元素 转化成python类型

# json_load.py

import json

strList = json.load(open("listStr.json"))
print strList

# [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]

strDict = json.load(open("dictStr.json"))
print strDict
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u5218'}

认识json:

import json

json模块提供了四个功能:dumpsdumploadsload,用于字符串 和 python数据类型间进行转换

 

1. json.loads()

把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:

 

 

# json_loads.py

import json

strList = '[1, 2, 3, 4]'

strDict = '{"city": "北京", "name": "大猫"}'

json.loads(strList) 
# [1, 2, 3, 4]

json.loads(strDict) # json数据自动按Unicode存储
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u732b'}

2. json.dumps()

实现python类型转化为json字符串,返回一个str对象 把一个Python对象编码转换成Json字符串

# json_dumps.py

import json
import chardet

listStr = [1, 2, 3, 4]
tupleStr = (1, 2, 3, 4)
dictStr = {"city": "北京", "name": "大猫"}

json.dumps(listStr)
# '[1, 2, 3, 4]'
json.dumps(tupleStr)
# '[1, 2, 3, 4]'

# 注意:json.dumps() 序列化时默认使用的ascii编码
# 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
# chardet.detect()返回字典, 其中confidence是检测精确度

json.dumps(dictStr) 
# '{"city": "\\u5317\\u4eac", "name": "\\u5927\\u5218"}'

chardet.detect(json.dumps(dictStr))
# {'confidence': 1.0, 'encoding': 'ascii'}

print json.dumps(dictStr, ensure_ascii=False) 
# {"city": "北京", "name": "大刘"}

chardet.detect(json.dumps(dictStr, ensure_ascii=False))
# {'confidence': 0.99, 'encoding': 'utf-8'}

3. json.dump()

将Python内置类型序列化为json对象后写入文件

# json_dump.py

import json

listStr = [{"city": "北京"}, {"name": "大刘"}]
json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)

dictStr = {"city": "北京", "name": "大刘"}
json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)

4. json.load()

读取文件中json形式的字符串元素 转化成python类型

# json_load.py

import json

strList = json.load(open("listStr.json"))
print strList

# [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]

strDict = json.load(open("dictStr.json"))
print strDict
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u5218'}

 

第二种:调用pickle模块

 

   1 import pickle
   2 
   3 def saveDbase(filename, ):
   4     file = open(filename, 'w')
   5     pickle.dump(object, file)          # pickle to file
   6     file.close( )                     # any file-like object will do
   7 
   8 def loadDbase(filename):
   9     file = open(filename, 'r')
  10     object = pickle.load(file)         # unpickle from file
  11     file.close( )                     # re-creates object in memory
  12     return object

认识pickle:

pickle提供了一个简单的持久化功能。可以将对象以文件的形式存放在磁盘上。

pickle模块只能在Python中使用,python中几乎所有的数据类型(列表,字典,集合,类等)都可以用pickle来序列化,

pickle序列化后的数据,可读性差,人一般无法识别。

------------------------------------------

pickle.dump(obj, file[, protocol])
  序列化对象,并将结果数据流写入到文件对象中。参数protocol是序列化模式,默认值为0,表示以文本的形式序列化。protocol的值还可以是1或2,表示以二进制的形式序列化。

------------------------------------------
pickle.load(file)
  反序列化对象。将文件中的数据解析为一个Python对象。

 

下面示例用到了 dump() 和 load() ,它们使用文件和类似文件的对象。这些函数的操作非常类似于我们刚才所看到的 dumps() 和 loads() ,区别在于它们还有另一种能力 — dump() 函数能一个接着一个地将几个对象转储到同一个文件。随后调用 load() 来以同样的顺序检索这些对象。下面显示了这种能力的实际应用:

 

  1. >>> a1 = 'apple'  
  2. >>> b1 = {1'One'2'Two'3'Three'}  
  3. >>> c1 = ['fee''fie''foe''fum']  
  4. >>> f1 = file('temp.pkl''wb')  
  5. >>> pickle.dump(a1, f1, True)  
  6. >>> pickle.dump(b1, f1, True)  
  7. >>> pickle.dump(c1, f1, True)  
  8. >>> f1.close()  
  9. >>> f2 = file('temp.pkl''rb')  
  10. >>> a2 = pickle.load(f2)  
  11. >>> a2  
  12. 'apple'  
  13. >>> b2 = pickle.load(f2)  
  14. >>> b2  
  15. {1'One'2'Two'3'Three'}  
  16. >>> c2 = pickle.load(f2)  
  17. >>> c2  
  18. ['fee''fie''foe''fum']  
  19. >>> f2.close()  

参考:http://blog.csdn.net/sinat_29552923/article/details/70833455

 

 

 

第三种:写入字节流

比如从网上获取一张图片地址:

import requests

url = 'http://xxxx/rand_code_captcha/'

res = requests.get(url, stream=True)
with open(pic_path + pic_name+'.bmp', 'wb') as f: 
    for chunk in res.iter_content(chunk_size=1024): 
        if chunk: 
            # filter out keep-alive new chunks 
            f.write(chunk)
            f.flush() 
            f.close()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值