python,day4,常用模块

目录

    • 1、time模块
    • 2、random模块
    • 3、OS模块
    • 4、sys模块
    • 5、shutil模块
    • 6、json&pickle模块
    • 7、shelve模块(了解)
    • 8、xml模块(了解)
    • 9、configparser模块
    • 10、hashlib 模块
    • 11、suprocess模块
    • 12、logging模块
    • 13、re模块

1、time模块

#一、time#时间分为三种格式:#1、时间戳:从1970年等到现在经历过的秒数#用于时间间隔的计算import timeprint(time.time())#2、格式化时间:2020-03-30 11:11:11#用于展示时间print(time.strftime('%Y-%m-%d %H:%M:%S '))#3、结构化的时间#用于获取时间的某一部分res = time.localtime()print(res)#二、datetime#求当前时间与三天后的时间import datetimeprint(datetime.datetime.now())print(datetime.datetime.now()) + datetime.timedelta(days=3)#三、时间模块需要掌握的操作#1、时间格式的转换#结构化(struct_time) -> 时间戳(timestamp)s_time = time.localtime()print(time.mktime(s_time))#时间戳(timestamp) -> 结构化(struct_time)tp_time = time.time()print(time.localtime(tp_time))#结构化(struct_time) -> 格式化(format_string)s_time=time.localtime()print(time.strftime('%Y-%m-%d %H:%M:%S',s_time))#格式化(format_string) -> 结构化(struct_time)print(time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')#格式化(format_string)-> 结构化(format_string) -> 时间戳(timestamp)  重点struct_time = time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')timestamp = time.mktime(struct_time)+7*86400print(timestamp)#格式化(format_string) <- 结构化(format_string) <- 时间戳(timestamp)  重点time.strftime('%Y-%m-%d %X',time.localtime(timestamp))#四、零碎知识点time.sleep(3) #控制代码执行时间print(time.asctime()) #直接显示当前格式化时间print(datetime.datetime.now())     #中国标准时间print(datetime.datetime.utcnow())  #世界标准时间print(datetime.datetime.fromordinal(333))  #将时间戳转化为字符串格式

2、random模块

import random
# print(random.random())                      #(0,1)  ---float  大于0且小于1之间的小数
# print(random.randint(1,3))                  #[1,3]   大于等于1且小于等于3之间的整数
# print(random.randrange([1,3]))              #[1,3) 大于等于1且小于3之间的整数
# print(random.choice([1,'23',[4,5]]))        #1或23或者[4,5]
# print(random.sample([1,'23',[4,5],2]))      #列表元素任意2个组合
# print(random.uniform(1,3))                  #大于1小于3的小鼠,如1.9895656664646
#
# item = [1,2,3,4,5,6]
# random.shuffle(item)                        #打乱item的顺序,相当于'洗牌'
# print(item)#应用:随机验证码
def make_code(size=4):                 #默认为4位验证码res = ''                           #定义res为字符串for i in range(size):              #默认循环4次s1=chr(random.randint(65,90))  #从26个大写字母随机取出一个字母s2=str(random.randint(0,9))    #从10个数字中随机取出一个数字res+=random.choice([s1,s2])    #字符串相加得到验证码return res
print(make_code(1))

3、OS模块

import os
# os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
# os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
# os.curdir  返回当前目录: ('.')
# os.pardir  获取当前目录的父目录字符串名:('..')
# os.makedirs('dirname1/dirname2')    可生成多层递归目录
# os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
# os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
# os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
# os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
# os.stat('path/filename')  获取文件/目录信息
# os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
# os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
# os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
# os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.environ['aaa']='11'  获取系统环境变量,规定:key与value必须都为字符串
os.path.abspath(path)  返回path规范化的绝对路径
os.path.split(path)  将path分割成目录和文件名二元组返回
os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是绝对路径,返回True
os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

4、sys模块

import sys
# 1 sys.argv           命令行参数List,第一个元素是程序本身路径
# 2 sys.exit(n)        退出程序,正常退出时exit(0)
# 3 sys.version        获取Python解释程序的版本信息
# 4 sys.maxint         最大的Int值
# 5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
# 6 sys.platform       返回操作系统平台名称#copy文件编写
# src_file = sys.argv[1]
# dst_file = sys.argv[2]
# with open(r'%s'%src_file,mode='rb')as read_f,\
#     open(r'%s'%dst_file,mode='wb')as write_f:
#     for line in read_f:
#         write_f.write(line)#打印进度条
import time
# def progress(percemt):
#     res = ''
#     for i in range(50):
#         res+='#'
#         time.sleep(0.5)
#         print('\r[%-50s]'%res,end='')
def progress(percent):if percent >1percent=1res = int(50 * percent) * '#'print('\r[%-50s] %d%%' % (res, 100 * percent), end='')a1=0a2=100000while a1 < a2:time.sleep(0.01)a1+=1024percent = a1 / a2res=int(50*percent)*'#'print('\r[%-50s] %d%%'%(res,100*percent),end='')

5、shutil模块


#高级的 文件、文件夹、压缩包 处理模块#1、 shutil.copyfileobj(fsrc, fdst[, length])# 将文件内容拷贝到另一个文件中import shutilshutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))#2、shutil.copyfile(src, dst)# 拷贝文件shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在#3、shutil.copymode(src, dst)#仅拷贝权限。内容、组、用户均不变shutil.copymode('f1.log', 'f2.log') #目标文件必须存在#4、shutil.copystat(src, dst)#仅拷贝状态的信息,包括:mode bits, atime, mtime, flagsshutil.copystat('f1.log', 'f2.log') #目标文件必须存在#5、shutil.copy(src, dst)#拷贝文件和权限shutil.copy('f1.log', 'f2.log')#6、shutil.copy2(src, dst)#拷贝文件和状态信息shutil.copy2('f1.log', 'f2.log')#7、shutil.ignore_patterns(*patterns)#shutil.copytree(src, dst, symlinks=False, ignore=None)#递归的去拷贝文件夹shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除#8、shutil.rmtree(path[, ignore_errors[, onerror]])#递归的去删除文件shutil.rmtree('folder1')#9、shutil.move(src, dst)#递归的去移动文件,它类似mv命令,其实就是重命名shutil.move('folder1', 'folder3')

6、json&pickle模块

#json&pickle模块
'''1、什么是序列化?3、内存中的数据类型 ---》序列化---》特定的格式(json格式或者pickle格式)4、内存中的数据类型 《---反序列化《---特定的格式(json格式或者pickle格式)土办法:{‘aa’:11}-->序列化str({‘aa’:11})--->'{'aa':11}'{‘aa’:11}<--反序列化str({‘aa’:11})<---'{'aa':11}'2、为什么要有序列化1、序列化得到的结果 =》特定的格式的内容有两种用途1、可用于存储 =》用于存档2、传输给其他平台使用 =》跨平台数据交互2、针对用途1的特定格式:可是一种专用的格式 =》pickle只有python可以识别针对用途2的特定格式:应该是一种通用的,能够被所有语言识别的格式 =》json3、怎么用import jsonjson模块#序列化的结果写入文件的复杂方法json_res=json.dumps([True,False,'aaa',1])# print(json_res,type(json_res))  #[true, false, "aaa", 1]with open('test.json',mode='wt',encoding='utf-8')as f:f.write(json_res)#将序列化的结果写入文件的简单方法with open('test.json',mode='wt',encoding='utf-8')as f:json.dumps([1,'aaa',True,False],f)#从文件读取json格式的字符串进行反序列化操作的复杂方法with open('test.json',mode='rt',encoding='utf-8')as f:json_res=f.read()l=json.loads(json_res)print(l,type(l))#从文件读取json格式的字符串进行反序列化操作的简单方法with open('test.json',mode='rt',encoding='utf-8')as f:l=json.loads(f)print(l,type(l))import picklepickle模块#序列化res = pickle.dumps({1,2,3,4,5})print(res,type(res))#反序列化s = pickle.loads(res)print(s,type(s))
'''

7、shelve模块(了解)

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型import shelvef=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}print(f['stu1_info']['hobby'])
f.close()

8、xml模块(了解)

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
<?xml version="1.0"?>
<data><country name="Liechtenstein"><rank updated="yes">2</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank updated="yes">5</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank updated="yes">69</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country>
</data>xml数据

9、configparser模块

'''
配置文件# 注释1; 注释2[section1]k1 = v1k2:v2user=egonage=18is_admin=truesalary=31[section2]k1 = v1'''
使用方法:import configparserconfig=configparser.ConfigParser()config.read('file.ini')#1、获取sectionsprint(config.sections())#2、获取某一section下的所有optionsprint(config.options('section1'))#3、获取itemsprint(config.items('section1'))
'''
'''

10、hashlib 模块

'''
1、什么是hashhash是一类算法,该算法接收传入的内容,经过运算得到一串hash值hash值的特点:1、传入的内容一样,得到的hash值必然一样 ==》明问2、不能由hash值反解成内容3、只要使用的hash算法不变,无论校验内容多大,得到的hash值的长度是固定的
2、hash的用途:1、密文传输与验证2、文件完整性校验3、用途import hashlibm=hashlib.md5()m.update('hello'.encode('utf-8'))m.update('world'.encode('utf-8'))res = m.hexdigest()  #'helloworld'print(res)1、模拟撞库cryptograph = 'asd78979zcx654qa65d4sa1c65f'passwd = ['asd1','qwe2','ads54']import  hashlibdic = {}for p in passwd:res = hashlib.md5(p.encode('utf-8'))dic[p]=res.hexdigest()print(dic)for k,v in dic.items():if v == cryptograph:print('撞库成功,铭文密码是'%k)break2、提升撞库的成本 =》密码加盐import  hashlibm = hashlib.md5()m.update('加'.encode('utf-8'))m.update('password'.encode('utf-8'))m.update('盐'.encode('utf-8'))print(m.hexdigest())     
'''

11、suprocess模块

import  subprocess
obj=subprocess.Popen('ls /',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,)
res = obj.stdout.read()   #正确输出
print(res.decode('utf-8'))
err_res=obj.stderr.read()   #错误输出
print(err_res.decode('utf-8'))

12、logging模块

import logging
日志级别与配置:# 一:日志配置logging.basicConfig(# 1、日志输出位置:1、终端 2、文件# filename='access.log', # 不指定,默认打印到终端# 2、日志格式format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',# 3、时间格式datefmt='%Y-%m-%d %H:%M:%S %p',# 4、日志级别# critical => 50# error => 40# warning => 30# info => 20# debug => 10level=30,)# 二:输出日志logging.debug('调试debug')logging.info('消息info')logging.warning('警告warn')logging.error('错误error')logging.critical('严重critical')'''# 注意下面的root是默认的日志名字WARNING:root:警告warnERROR:root:错误errorCRITICAL:root:严重critical'''日志配置字典"""
logging配置
"""import os# 1、定义三种日志输出格式,日志中可能用到的格式化串如下
# %(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用户输出的消息# 2、强调:其中的%(name)s为getlogger时指定的名字
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \'[%(levelname)s][%(message)s]'simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'test_format = '%(asctime)s] %(message)s'# 3、日志配置字典
LOGGING_DIC = {'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': standard_format},'simple': {'format': simple_format},'test': {'format': test_format},},'filters': {},'handlers': {#打印到终端的日志'console': {'level': 'DEBUG','class': 'logging.StreamHandler',  # 打印到屏幕'formatter': 'simple'},#打印到文件的日志,收集info及以上的日志'default': {'level': 'DEBUG','class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,日志轮转'formatter': 'standard',# 可以定制日志文件路径# BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # log文件的目录# LOG_PATH = os.path.join(BASE_DIR,'a1.log')'filename': 'a1.log',  # 日志文件'maxBytes': 1024*1024*5,  # 日志大小 5M'backupCount': 5,'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了},'other': {'level': 'DEBUG','class': 'logging.FileHandler',  # 保存到文件'formatter': 'test','filename': 'a2.log','encoding': 'utf-8',},},'loggers': {#logging.getLogger(__name__)拿到的logger配置'': {'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕'level': 'DEBUG', # loggers(第一层日志级别关限制)--->handlers(第二层日志级别关卡限制)'propagate': False,  # 默认为True,向上(更高level的logger)传递,通常设置为False即可,否则会一份日志向上层层传递},'专门的采集': {'handlers': ['other',],'level': 'DEBUG','propagate': False,},},
}日志配置字典LOGGING_DIC使用:
import settings# !!!强调!!!
# 1、logging是一个包,需要使用其下的config、getLogger,可以如下导入
# from logging import config
# from logging import getLogger# 2、也可以使用如下导入
import logging.config # 这样连同logging.getLogger都一起导入了,然后使用前缀logging.config.# 3、加载配置
logging.config.dictConfig(settings.LOGGING_DIC)# 4、输出日志
logger1=logging.getLogger('用户交易')
logger1.info('egon儿子alex转账3亿冥币')# logger2=logging.getLogger('专门的采集') # 名字传入的必须是'专门的采集',与LOGGING_DIC中的配置唯一对应
# logger2.debug('专门采集的日志')common.py

13、re模块

常用匹配模式:http://blog.csdn.net/yufenghyc/article/details/51078107
# =================================匹配模式=================================
#一对一的匹配
# 'hello'.replace(old,new)
# 'hello'.find('pattern')#正则匹配
import re
#\w与\W
print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
print(re.findall('\W','hello egon 123')) #[' ', ' ']#\s与\S
print(re.findall('\s','hello  egon  123')) #[' ', ' ', ' ', ' ']
print(re.findall('\S','hello  egon  123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']#\n \t都是空,都可以被\s匹配
print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']#\n与\t
print(re.findall(r'\n','hello egon \n123')) #['\n']
print(re.findall(r'\t','hello egon\t123')) #['\n']#\d与\D
print(re.findall('\d','hello egon 123')) #['1', '2', '3']
print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']#\A与\Z
print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$
^ 指定匹配必须出现在字符串的开头或行的开头。
\A 指定匹配必须出现在字符串的开头(忽略 Multiline 选项)。
$ 指定匹配必须出现在以下位置:字符串结尾、字符串结尾的 \n 之前或行的结尾。
\Z 指定匹配必须出现在字符串的结尾或字符串结尾的 \n 之前(忽略 Multiline 选项)。
#^与$
print(re.findall('^h','hello egon 123')) #['h']
print(re.findall('3$','hello egon 123')) #['3']# 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
#.
print(re.findall('a.b','a1b')) #['a1b']
print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b','a\nb')) #[]
print(re.findall('a.b','a\nb',re.S)) #['a\nb']
print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样#*
print(re.findall('ab*','bbbbbbb')) #[]
print(re.findall('ab*','a')) #['a']
print(re.findall('ab*','abbbb')) #['abbbb']#?
print(re.findall('ab?','a')) #['a']
print(re.findall('ab?','abbb')) #['ab']
#匹配所有包含小数在内的数字
print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']#.*默认为贪婪匹配
print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']#.*?为非贪婪匹配:推荐使用
print(re.findall('a.*?b','a1b22222222b')) #['a1b']#+
print(re.findall('ab+','a')) #[]
print(re.findall('ab+','abbb')) #['abbb']#{n,m}
print(re.findall('ab{2}','abbb')) #['abb']
print(re.findall('ab{2,4}','abbb')) #['abb']
print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'#[]
print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']#\# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c']#():分组
print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
print(re.findall('href="(.*?)"','点击'))#['http://www.baidu.com']
print(re.findall('href="(?:.*?)"','点击'))#['href="http://www.baidu.com"']#|
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部