python内置模块(三)

hashlib模块

通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。

Python2中使用hashlib:

import hashlib
m = hashlib.md5()
# m <md5 HASH object @ 0x0000000001E5C800>
src = "ling"
m.update(src)
print(m.hexdigest())
# 24c10be286b009f797d53126790fcfd8

Python3中使用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模块

有时候数据读写不一定是文件,也可以在内存中读写。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())

BytesIO模块

StringIO操作的只能是str,如果要操作二进制数据,就需要用到BytesIO。
from io import BytesIO
bytesIO = BytesIO()
bytesIO.write("中文".encode("utf-8"))
print(bytesIO.getvalue())  # 读取内容
注意:写入的不是str,而是utf-8编码的bytes。
BytesIO也可以像读取文件一样读取里面的内容:
from io import BytesIO
bytesIO = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
bytesIO.read()
b'\xe4\xb8\xad\xe6\x96\x87'

Json模块

json指的是JavaScript对象表示法,json是轻量级的文本数据交换格式。
用法:
loads      把字符串转换为python对象(如字典、列表等)
dumps    把python对象转换成字符串
load        把文件转换成python对象
dump      把python对象写入文件
 
对字符串进行操作,字符串转换成python对象:
import json
test = '''[{"a":1, "aa":11, "aaa":111},{"b":2, "bb":22, "bbb":333}]'''
print(type(test))           # <type 'str'>
newTest = json.loads(test)  # 把字符串转换成python对象
print(type(newTest))        # <type 'list'>
print(newTest[0]["a"])      # 1

针对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'>

猜你喜欢

转载自www.cnblogs.com/yangjian319/p/8960927.html