python学习-第12课

一、内置模块3

1.1.hashlib模块

此模块用于加密相关的操作,主要有SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法。

1.1.1.md5加密

Python3 需要把src转换成bytes类型     bytes(src, encoding=“utf-8”)
import hashlib
md5hash=hashlib.md5("multi code".encode("utf-8"))   #multi code是加密时使用的混合码
srcString=bytes("this is hashlib mad5 test",encoding="utf-8")#加密源码
md5hash.update(srcString)
print(md5hash.hexdigest())
结果
75f948b0419cbc742f4791926cb6bde6

1.1.2.sha1加密

import hashlib
sh1hash = hashlib.sha1()
srcStrings = "this is sha1 test".encode("utf-8")
sh1hash.update(srcStrings)
print(sh1hash.hexdigest())
结果
e39b9f010cbe3e68309fa514d5bcd0e976c1dcd3

1.1.3.sha256加密

import hashlib
sha256hash=hashlib.sha256()
srcString="this is sha256 test".encode("utf-8")
sha256hash.update(srcString)
print(sha256hash.hexdigest())
结果
b1055df57748c033cb908364aeb520662160fef2b9b61b0fb06fd2f1222fe67f

1.1.4.sha384加密

import hashlib
sha384hash=hashlib.sha384()
sha384hash.update("this is sha384 test".encode("utf-8"))
print(sha384hash.hexdigest())
结果
82e59c54139d068c6c075b904081be50b4a57568568d8258191fd3b640e51b7b3e8108518910f37e4579020102eff0fd

1.1.5.sha512加密

import hashlib
sha512hash=hashlib.sha512("sha512".encode("utf-8")) #sha512加密混合码
sha512hash.update("this is sha512 test".encode("utf-8"))
print(sha512hash.hexdigest())
结果
ac4e7bcfd6b49ba67a86b6d742a52987767d2d76be1dbd910eac6a284af33ce43e02164a863d557eeb6282d165950c88e87a382c47aac4df8474c4cf2ac50237

1.1.6.hmac加密

import hmac
h=hmac.new("hmac".encode("utf-8"))
h.update("this is hmac test".encode("utf-8"))
print(h.hexdigest())
结果
0e18120f766bea1edab864169b97f1e3

1.2.StringIO模块

StringIO用于将对象存储在缓存中,便于快速存储、读取
StringIO的函数跟String函数类似
from io import StringIO
s=StringIO()

1.2.1.s.write(strs)函数

从读写位置将参数strs写入给对象s。参数strs为str或unicode类型。读写位置被移动。
from io import StringIO
s=StringIO()
s.write("this StringIO test\n")
s.write("python StringIO")

1.2.2.s.getvalue()函数

此函数没有参数,返回对象s中的所有数据。
from io import StringIO
s=StringIO()
s.write("this StringIO test\n")
s.write("python StringIO")
print(s.getvalue())
结果
this StringIO test
python StringIO

1.2.3.s.read(n)函数

参数n限定读取长度,int类型;缺省状态为从当前读写位置读取对象s中存储的所有数据。读取结束后,读写位置被移动。
示例
from io import StringIO
s=StringIO("hello\nworld\nthis\nis\nStringIO\ntest")
print(s.read(6))
结果
hello

1.2.4.s.readline(n)函数

参数n限定读取的结束位置,int类型,缺省状态为None:从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
from io import StringIO
s=StringIO("hello\nworld\nthis\nis\nStringIO\ntest")
print(s.readline())
print(s.readline())
print(s.readline())
结果
hello


world


this

1.2.5.s.readlines(n)函数

参数n为int类型,缺省状态为读取所有行并作为列表返回,除此之外从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
from io import StringIO
s=StringIO("hello\nworld\nthis\nis\nStringIO\ntest")
print(s.readlines(1))
print(s.readlines())
结果
['hello\n']
['world\n', 'this\n', 'is\n', 'StringIO\n', 'test']

1.2.6.s.writelines(n)函数

从读写位置将list写入给对象s。参数list为一个列表,列表的成员为str或unicode类型。读写位置被移动。
from io import StringIO
l=["a","b","c"]
s=StringIO()
s.writelines(l)
print(s.getvalue())
结果
abc

1.2.7.s.truncate(n)函数

从读写位置起切断数据,参数size限定裁剪长度,缺省值为None。
from io import StringIO
stringIO = StringIO()
stringIO.write("hello world\n")
stringIO.write("this stringIO test")
print(stringIO.getvalue())
stringIO.truncate(0)  #清除缓存
print(stringIO.getvalue())

1.2.8.s.flush()函数

刷新内部缓冲区

1.2.9.s.close()函数

from io import StringIO
l=["a","b","c"]
s=StringIO()
s.writelines(l)
print(s.getvalue())
s.close()
print("flush 刷新后:{0}".format(s.getvalue()))
结果
Traceback (most recent call last):
abc
  File "D:/pythoncode/LivePython02/15第十二课/test1208.py", line 12, in <module>
    print("flush 刷新后:{0}".format(s.getvalue()))
ValueError: I/O operation on closed file

1.2.10.s.tell()函数

返回当前读写位置

1.3.json模块

1.3.1.json.loads函数

对数据进行解码,用于把JSON对象转换python对象
JSON 解码为 Python 类型转换对应表:

SON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

示例
1.txt内容
{"no": 1, "name": "python", "message": "this is json message test"}

import codecs,json
with codecs.open("1.txt","r") as f:
    values=json.loads(f.read())
    json_name=values["message"]  #打印message的key value值
    print(type(values))  #打印loads数据类型
    print(json_name)
结果
<class 'dict'>
this is json message test

1.3.2.json.dumps函数

对数据进行编码,把python对象转换成JSON对象
Python 编码为 JSON 类型转换对应表
Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

示例

import json

# Python 字典类型转换为 JSON 对象
data = {
    "no" : 1,
    "name" : "python",
    "content" : "Python Object change to JSON Object"
}

json_str=json.dumps(data)
print ("Python 原始数据:{0}".format(data))
print ("data数据类型:{0}".format(type(data)))
print ("JSON 对象:{0}".format(json_str))
print ("json_str数据类型:{0}".format(type(json_str)))
结果
Python 原始数据:{'no': 1, 'name': 'python', 'content': 'Python Object change to JSON Object'}
data数据类型:<class 'dict'>
JSON 对象:{"no": 1, "name": "python", "content": "Python Object change to JSON Object"}
json_str数据类型:<class 'str'>

1.3.3.json.dump函数

用于对文件进行编码
示例
import json

data = {
    "no" : 1,
    "name" : "python",
    "content" : "Python Object change to JSON Object"
}

with open('data.json', 'w') as f:
    json.dump(data, f)
生成data.json文件,内容如下:

1.3.3.json.load函数

用于对文件进行解码

示例
data.json文件内容如下:
{"no": 1, "name": "python", "content": "Python Object change to JSON Object"}

import codecs,json

with codecs.open("data.json","r") as f:
    data=json.load(f)
    print(data["name"])

结果
python

1.3.4.python2 json中文显示问题

python2 对中文显示不友好,可以通过ensure_ascii=False解密此问题
import json
a = dict(hello="python2 json中文显示成十六进制问题")
print(a)
print(a["hello"])
print(str(a))
print(json.dumps(a, ensure_ascii=False))
结果
{'hello': 'python2 json\xe4\xb8\xad\xe6\x96\x87\xe6\x98\xbe\xe7\xa4\xba\xe6\x88\x90\xe5\x8d\x81\xe5\x85\xad\xe8\xbf\x9b\xe5\x88\xb6\xe9\x97\xae\xe9\xa2\x98'}
python2 json中文显示成十六进制问题
{'hello': 'python2 json\xe4\xb8\xad\xe6\x96\x87\xe6\x98\xbe\xe7\xa4\xba\xe6\x88\x90\xe5\x8d\x81\xe5\x85\xad\xe8\xbf\x9b\xe5\x88\xb6\xe9\x97\xae\xe9\xa2\x98'}
{"hello": "python2 json中文显示成十六进制问题"}






猜你喜欢

转载自blog.csdn.net/biankm_gz/article/details/80108508
今日推荐