通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。
Python2中使用hashlib:
import hashlib m = hashlib.md5() # m <md5 HASH object @ 0x0000000001E5C800> src = "ling" m.update(src) print(m.hexdigest())# 24c10be286b009f797d53126790fcfd8Python3中使用hashlib:
import hashlib m = hashlib.md5() # m = hashlib.md5("123".encode("utf-8")) # 加入一个随机数 # m <md5 HASH object @ 0x0000000001E5C800> src = bytes("ling",encoding="utf-8") src1 = bytes("zhangsan",encoding="utf-8") m.update(src) m.update(src1) print(m.hexdigest())如果数据量很大,可以分块多次调用update()。
有时候数据读写不一定是文件,也可以在内存中读写。StringIO就是在内存中读写str。
from io import StringIO # StringIO只能存字符串 stringIO = StringIO() stringIO.write("hello,world\n") stringIO.write("hello,python") print(stringIO.getvalue()) #hello,world #hello,python stringIO.truncate(0) # 清空所有写入的内容 stringIO.flush() # 刷新内部缓冲区 print(stringIO.getvalue()) #没有输出,内容已经被清空了StringIO也可以像读取文件一样读取:
from io import StringIO stringIO = StringIO("hello\nworld") while True: s = stringIO.readline() if s == "": break print(s.strip())
针对python2乱码问题,使用json解决:
import json a = dict(hello="你好") print(a) # {'hello': '\xe4\xbd\xa0\xe5\xa5\xbd'} print(a["hello"]) # 你好 print(json.dumps(a,ensure_ascii=False)) # 把python对象转换成字符串 # {"hello": "你好"}对文件进行操作,文件和python对象相互转换:
import json test = {"a":1, "b":2} with codecs.open("1.txt","w") as f: json.dump(test, f) # 把python对象写入文件 with codecs.open("1.txt","r") as f: aa = json.load(f) # 把文件转换成python对象,aa是unicode类型 print(aa) # {u'a': 1, u'b': 2} print(type(aa)) # <type 'dict'>
转载于:https://www.cnblogs.com/yangjian319/p/8960927.html