学习内容:
Python模块介绍
1、time &datetime模块
2、random
3、shutil
4、shelve
5、xml处理
6、configparser
7、hashlib
8、logging模块
9、re正则表达式
一、time &datetime模块
print (time.time()/(3600*24*365)) #返回自1970年1月1日至今的秒数
print (time.altzone/(3600)) #返回与UTC时间的时间差
print (time.clock()) #
print (time.asctime()) # 返回时间 美国格式
print (time.ctime()) #返回时间 格式同上
print (time.gmtime()) #返回UTC时间的时间对象
print (time.localtime())#返回本地时间的时间对象
#字符串转成时间戳
t1=time.strptime('2016-11-11','%Y-%m-%d')
print ('T1-->',t1)
t1_tamp=time.mktime(t1)
print ('T1_tamp===>',t1_tamp)
#将时间戳转成字符串
t2=time.gmtime(t1_tamp+86400)
print ('T2',t2)
t2_tamp=time.strftime('%Y-%m-%d',t2)
print ('T2_tamp',t2_tamp)
print ('#------------------datetime----------------------')
print (datetime.datetime.now())
print (datetime.datetime.fromtimestamp(time.time()))
print (datetime.datetime.now() + datetime.timedelta(days=3)) #(cls, days=0, seconds=0, microseconds=0,
#milliseconds=0, minutes=0, hours=0, weeks=0):
now = datetime.datetime.now()
print (now.replace(month=1,day=3))
二、random
随机数模块
print (random.random()) #生成0到1之间的小数
print (random.randint(1,10)) #包含10
print (random.randrange(1,10)) #不包含10
print (random.sample(range(100),5)) #在前面一堆里选出随机选出5个字符
print (string.ascii_letters) #包含全部字符
print (string.digits) #包含全部数字
str_source = string.digits + string.ascii_letters #包含全部字母和数字
kkk=''.join(random.sample(str_source,6)) #生成随机数的方法
print (kkk)
check_code='' #生成随机数的方法
for i in range(6):
current_code=random.randint(0,6)
if current_code != i:
code=chr(random.randint(65,90))
else:
code=random.randint(0,9)
check_code += str(code)
print (check_code)
三、shutil
文件压缩模块
# shutil.copytree() #cp -rp tgz gztar tar 只打包 zip 压缩
# shutil.copyfileobj(fsrc, fdst[, length]) #将文件内容拷贝到另一个文件中,可以部分内容
# shutil.copyfile(src, dst) #拷贝文件
# shutil.copymode(src, dst) #仅拷贝权限。内容、组、用户均不变
# shutil.copystat(src, dst) #拷贝状态的信息,包括:mode bits, atime, mtime, flags
# shutil.copy(src, dst) #拷贝文件和权限
# shutil.copy2(src, dst) #拷贝文件和状态信息
# shutil.copytree(src, dst, symlinks=False, ignore=None) #递归的去拷贝文件 相当于cp -rp
# shutil.rmtree(path[, ignore_errors[, onerror]]) #递归的去删除文件
# shutil.move(src, dst) #递归的去移动文件
# shutil.make_archive(base_name, format,...) '''
# 创建压缩包并返回文件路径,例如:zip、tar
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的
四、shelve
文件持久化模块
正向:
d = shelve.open('shelve_test')
def sayHi(name,age):
print ('Hi %s,you are %s years old!'%(name,age))
info={'name':'alex','age':18,'sex':'F'}
name=['zhaoli','qiansan','lisi']
d['sayHi2']=sayHi
d['info2']=info
d['name2']=name
反向:
f=shelve.open('shelve_test')
def sayHi(name,age):
print ('Hi %s,you are %s years old!'%(name,age))
print (f['sayHi2']('alex',18))
print (f['info2']['sex'])
print (f['name2'])
五、xml处理
与json类似,是变量序列化的工具。python里对XML文件的增删改查。
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test")
root = tree.getroot()
print(root.tag)
# 遍历xml文档
for child in root:
print(child.tag, child.attrib)
for i in child:
print('\t',i.tag, i.text)
# 只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)
七、configparser
解析配置模块
import configparser
config = configparser.ConfigParser()
#类似于数组
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
八、hashlib
文件安全和文件加密模块
import hashlib
m=hashlib.md5()
m.update(b'alex')
print (m.hexdigest())
m.update(b'li')
print (m.hexdigest())
m2 = hashlib.md5()
m2.update(b'alexli')
print (m.hexdigest())
hash = hashlib.sha1()
hash.update(b'alexli')
print ('SHA1',hash.hexdigest())
hash2 = hashlib.sha256()
hash2.update(b'alexli')
print ('SHA2',hash2.hexdigest())
hash5 = hashlib.sha512()
hash5.update(b'alexli')
print ('SHA5',hash5.hexdigest())
import hmac
hmaac_obj = hmac.new(b'salt',b'hello')
print ('HHHMAC:',hmaac_obj.hexdigest())
九、logging模块
记录日子模块
python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。
logging模块与log4j的机制是一样的,只是具体的实现细节不同。模块提供logger,handler,filter,formatter。
logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。
(1)通过logging.basicConfig函数对输出的日志格式进行配置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%d %b %Y %H:%M:%S %a',
filename='myapp.log',
filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
(2)将log同时输出到屏幕和文件
import logging
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# datefmt='%d %b %Y %H:%M:%S',
# filename='myapp.log',
# filemode='w')
logger = logging.getLogger('calc')
logger.setLevel(logging.WARNING)
#################################################################################################
#定义一个StreamHandler
console = logging.StreamHandler('calc')
console.setLevel(logging.INFO)
#################################################################################################
#定义一个FileHandler
file_log = logging.FileHandler('myapp.log')
file_log.setLevel(logging.INFO)
#################################################################################################
#定义输出格式
formatter1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter2 = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
#################################################################################################
#将输出格式添加到标准输出中
console.setFormatter(formatter1)
file_log.setFormatter(formatter2)
#################################################################################################
#将输出格式绑定绑定到logger
logger.addHandler(file_log)
logger.addHandler(console)
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
十、re正则表达式
正则表达式模块
re.match 从头开始匹配re.search 匹配包含re.findall 把所有匹配到的字符放到以列表中的元素返回re.split 以匹配到的字符当做列表分隔符re.sub 匹配字符并替换'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)'$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以'*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']'+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']'?' 匹配前一个字符1次或0次'{m}' 匹配前一个字符m次'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC''(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c'\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的'\Z' 匹配字符结尾,同$'\d' 匹配数字0-9'\D' 匹配非数字'\w' 匹配[A-Za-z0-9]'\W' 匹配非[A-Za-z0-9]'s' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
浙公网安备 33010602011771号