博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python--模块2
阅读量:7232 次
发布时间:2019-06-29

本文共 9038 字,大约阅读时间需要 30 分钟。

hashlib模块

1.Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。

什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。

摘要算法就是通过摘要函数f()对任意长度的数据data计算出固定长度的摘要digest,目的是为了发现原始数据是否被人篡改过。

摘要算法之所以能指出数据是否被篡改过,就是因为摘要函数是一个单向函数,计算f(data)很容易,但通过digest反推data却非常困难。而且,对原始数据做一个bit的修改,都会导致计算出的摘要完全不同。

我们以常见的摘要算法MD5为例,计算出一个字符串的MD5值:

#!/usr/bin/env python# -*- coding:utf-8 -*-import hashlibmd5_obj = hashlib.md5()md5_obj.update("123456".encode("utf-8"))print(md5_obj.hexdigest())

如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的:

#!/usr/bin/env python# -*- coding:utf-8 -*-import hashlibmd5_obj = hashlib.md5()md5_obj.update("123456".encode("utf-8"))md5_obj.update("000000".encode("utf-8"))print(md5_obj.hexdigest()) #42c23b08884a131940e1d12196ed935cmd5_obj = hashlib.md5()md5_obj.update("123456000000".encode("utf-8"))print(md5_obj.hexdigest()) #42c23b08884a131940e1d12196ed935c

应用根据MD5值判断两个文件是否相同:

import osimport  hashlibdef get_md5(file,n=10240):    with open(file,mode="rb") as f:        md5_obj = hashlib.md5()        file_size =  os.path.getsize(file)        while file_size > 0:            md5_obj.update(f.read(n))            file_size -= n        return md5_obj.hexdigest()def comper(file1,file2):    return  get_md5(file1) == get_md5(file2)print(comper("1.txt","2.txt"))

configparser模块

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes  [bitbucket.org]User = hg  [topsecret.server.com]Port = 50022ForwardX11 = no

代码生成:

import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {    "ServerAliveInterval":"45",    "Compression":"yes",    "CompressionLevel":"9",    "ForwardX11":"yes"}config["bitbucket.org"] = {"User":"hg"}config["topsecret.server.com"] = {    "Port":"50022",    "ForwardX11":"no"}with open("examle.ini","w") as f:    config.write(f)

查找文件:

import configparserconfig = configparser.ConfigParser()print(config.sections()) #[]config.read("examle.ini") #['bitbucket.org', 'topsecret.server.com']print(config.sections())print("bytebong.com" in config) #Falseprint("bitbucket.org" in config) #Trueprint(config["bitbucket.org"]["User"]) #hgprint(config["DEFAULT"]["ForwardX11"]) #yesprint(config["bitbucket.org"]) #
for key in config["bitbucket.org"]: #注意,有default会默认default的键 print(key)print(config.options("bitbucket.org")) #['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']print(config.items("bitbucket.org")) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]print(config.get("bitbucket.org","Compression")) #yes

增删改操作

import configparserconfig = configparser.ConfigParser()config.read("examle.ini")config.add_section("yuan")config.remove_section('bitbucket.org')config.remove_option("topsecret.server.com","port")config.set("topsecret.server.com","k1","111")config.set("yuan","k2","222")config.write(open("examle.ini2","w"))config.set('topsecret.server.com','k1','11111')config.set('yuan','k2','22222')config.write(open('new2.ini', "w"))

logging模块

1.函数简单配置

import logginglogging.debug('debug message')logging.info('info message')logging.warning('warning message')logging.error('error message')logging.critical('critical message')#默认屏幕打印warning以上级别的

默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

2.默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。
灵活配置日志级别,日志格式,输出位置:

import logginglogging.basicConfig(level=logging.DEBUG,                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',                    datefmt='%a, %d %b %Y %H:%M:%S',                    filename='test.log',                    filemode='w')logging.debug('debug message')logging.info('info message')logging.warning('warning message')logging.error('error message')logging.critical('critical message')

配置参数:

logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。format:指定handler使用的日志显示格式。datefmt:指定日期时间格式。level:设置rootlogger(后边会讲解具体概念)的日志级别stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。format参数中可能用到的格式化串:%(name)s Logger的名字%(levelno)s 数字形式的日志级别%(levelname)s 文本形式的日志级别%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有%(filename)s 调用日志输出函数的模块的文件名%(module)s 调用日志输出函数的模块名%(funcName)s 调用日志输出函数的函数名%(lineno)d 调用日志输出函数的语句所在的代码行%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒%(thread)d 线程ID。可能没有%(threadName)s 线程名。可能没有%(process)d 进程ID。可能没有%(message)s用户输出的消息

3.

import logginglogger = logging.getLogger()# 创建一个handler,用于写入日志文件fh = logging.FileHandler('test.log',encoding='utf-8') # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh.setLevel(logging.DEBUG)fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 logger.addHandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')

序列化模块

什么叫序列化——将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化。

序列化的目的:1.以某种存储形式使自定义对象持久化;

2.将对象从一个地方传递到另一个地方。         3.使程序更具维护性。

1.json

Json模块提供了四个功能:dumps、dump、loads、load

import jsondic = {'k1':'v1','k2':'v2','k3':'v3'}str_dic = json.dumps(dic)  #序列化:将一个字典转换成一个字符串print(str_dic) #{"k1": "v1", "k2": "v2", "k3": "v3"}3", "k1": "v1", "k2": "v2"}#注意,json转换完的字符串类型的字典中的字符串是由""表示的
import jsondic = {'k1':'v1','k2':'v2','k3':'v3'}str_dic = json.dumps(dic)  #序列化:将一个字典转换成一个字符串print(str_dic) #{"k1": "v1", "k2": "v2", "k3": "v3"}dic2 = json.loads(str_dic)  #反序列化:将一个字符串格式的字典转换成一个字典,注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示print(dic2)  #{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}list_dic = [1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]str_dic = json.dumps(list_dic) #也可以处理嵌套的数据类型print(str_dic) #[1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]list_dic2 = json.loads(str_dic)print(list_dic2) #[1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
import jsonf = open("json_file","w")dic = {"k1":"v1"}json.dump(dic,f)    #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件f.close()f = open("json_file","r")dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回f.close()print(dic2) #{'k1': 'v1'}
import jsonf = open('file','w')json.dump({'国籍':'中国'},f)ret = json.dumps({'国籍':'中国'})f.write(ret+'\n')json.dump({'国籍':'美国'},f,ensure_ascii=False)ret = json.dumps({'国籍':'美国'},ensure_ascii=False)f.write(ret+'\n')f.close()
Serialize obj to a JSON formatted str.(字符串表示的json对象) Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。 default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. sort_keys:将数据根据keys的值进行排序。 To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
#格式化输出import jsondata = {'username':['李华','二愣子'],'sex':'male','age':16}json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)print(json_dic2)

json,用于字符串 和 python数据类型间进行转换

2.pickle

用于python特有的类型 和 python的数据类型间进行转换

pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化)

import pickledic = {'k1':'v1','k2':'v2','k3':'v3'}str_dic = pickle.dumps(dic)print(str_dic)  #一串二进制内容b'\x80\x03}q\x00(X\x02\x00\dic2 = pickle.loads(str_dic)print(dic2)    #字典{'k1':'v1','k2':'v2','k3':'v3'}
import pickleimport timestruct_time  = time.localtime(1000000000)print(struct_time) #time.struct_time(tm_year=2001, tm_mon=9, tm_mday=9, tm_hour=9, tm_min=46, tm_sec=40, tm_wday=6, tm_yday=252, tm_isdst=0f = open('pickle_file','wb')pickle.dump(struct_time,f)f.close()f = open('pickle_file','rb')struct_time2 = pickle.load(f)print(struct_time2) #time.struct_time(tm_year=2001, tm_mon=9, tm_mday=9, tm_hour=9, tm_min=46, tm_sec=40, tm_wday=6, tm_yday=252, tm_isdst=0

转载地址:http://nzvfm.baihongyu.com/

你可能感兴趣的文章
poj2771
查看>>
(转)反射-实例化类
查看>>
OGRE 阴影技术官方文档
查看>>
Trie 树内存消耗问题
查看>>
提供一个Cookies操作类(支持带域名与不带域名)IP和localhost域名调试
查看>>
iPhone的Push(推送通知)功能原理浅析
查看>>
php curl打开网页
查看>>
工信部提醒消费者谨防手机预置恶意插件
查看>>
金山发布3月安全报告 肉鸡网银挂马成安全成焦点
查看>>
poj3194
查看>>
OGRE手札-39 碰撞检测
查看>>
重读<算法导论>
查看>>
Oracle 11g Release 1 (11.1) 游标——SQL 游标(隐式)
查看>>
(笔试题)应聘iphone开发工程师,iphone和Objective-C的笔试题? (http://www.cocoachina.com/bbs/simple/?t44281.html)...
查看>>
欧拉函数
查看>>
C++之private虚函数
查看>>
水晶易表调用C#的WebService,返回数据集合
查看>>
用groovy写抓票程序
查看>>
fieldset 居中
查看>>
exynos4412,tegra3,msm8960性能对比,参考对照exynos4210
查看>>