python--模块2

hashlib模块

1.Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。
什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它经过一个函数,把任意长度的数据转换为一个长度固定的数据串(一般用16进制的字符串表示)。python

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

摘要算法之因此能指出数据是否被篡改过,就是由于摘要函数是一个单向函数,计算f(data)很容易,但经过digest反推data却很是困难。并且,对原始数据作一个bit的修改,都会致使计算出的摘要彻底不一样。json

咱们以常见的摘要算法MD5为例,计算出一个字符串的MD5值:数据结构

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

若是数据量很大,能够分块屡次调用update(),最后计算的结果是同样的:ide

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

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

import os
import  hashlib
def 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 = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

代码生成:ui

import configparser
config = 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 configparser
config = configparser.ConfigParser()
print(config.sections()) #[]

config.read("examle.ini") #['bitbucket.org', 'topsecret.server.com']
print(config.sections())

print("bytebong.com" in config) #False
print("bitbucket.org" in config) #True

print(config["bitbucket.org"]["User"]) #hg
print(config["DEFAULT"]["ForwardX11"]) #yes

print(config["bitbucket.org"]) #<Section: 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

增删改操做debug

import configparser
config = 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 logging
logging.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 logging

logging.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 logging

logger = 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 json
dic = {'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 json
dic = {'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 json
f = 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 json
f = 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 json
data = {'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 pickle
dic = {'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 pickle
import time
struct_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=0
f = 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