os 模块
import os
# # 1 获取某一个文件夹下所有子文件以及子文件夹的名字
# res = os.listdir('.')
# print(res)
# # 2 读取某个"文件大小的属性"
# for i in res:
# size = os.path.getsize(i)
# print(size)
# 3 os.remove() 删除一个文件
# 4 os.rename(oldname,newname) 重命名文件/目录
# 5 os.system(r"dir C:\\a") 运行系统命令 -> dir[查看] 该路径下的文件有什么子文件夹/文件
# 6 print(os.environ) 获取系统环境变量,得到的是一个字典,根据字典特性,
# 可以将"某东西"通过-> environ[字符串]=字符串 <-直接加入系统环境变量中
# 7 os.path系列
# print(__file__)
# print(os.path.abspath(__file__))
# print(os.path.abspath('.'))
# res = os.path.split('/a/b/c/d.txt')
# print(res)
# print(os.path.dirname('/a/b/c/d.txt')) # 获取其上一级名字
# print(os.path.basename('/a/b/c/d.txt')) # 获取其最后的名字
# # 在python 3.5之后,推出了一个新的模块 pathlib
#
# from pathlib import Path
#
# # 魅力 x1
# p = Path(__file__)
# res = p.parent.parent
# print(res)
#
# # 魅力 x2
# res = Path('/a/b/c') / 'd/e.txt'
# print(res)
# 掌握:
print(os.path.isfile(r'C:\aaa')) # 是否存在文件
print(os.path.dirname(r'c:\aaa\bbb'))
print(os.path.join('a,', 'C:' 'b', 'c', 'd', ))
print(os.path.normpath('/a/b/c/d/../..'))
sys 模块
import sys
import os
'''复制文件的工具(version 2.0)---使用sys.argv功能'''
length = len ( sys. argv)
if length != 3 :
raise 'The number of parameters is incorrect'
src_file = sys. argv[ 1 ]
dst_file = sys. argv[ 2 ]
if src_file == dst_file:
raise 'Duplicate file names'
if not os. path. isfile( src_file) :
raise 'The file does not exist'
if os. path. isfile( dst_file) :
raise 'The file already exists'
with open ( r'%s' % src_file, mode= 'rb' ) as f1, \
open ( r'%s' % dst_file, mode= 'wb' ) as f2:
while True :
res = f1. read( 1024 )
if not res:
break
f2. write( res)
random 模块
"""随机模块"""
import random
random. random( )
random. randint( - 6 , 6 )
random. randrange( - 6 , 6 )
random. uniform( - 8 , 8 )
"""
random.randrange(3, 30, 6)
它将生成 3 到 30 之间 "步长为>>>6" 的整数,如 3, 9, 15
"""
random. randrange( 3 , 20 , 6 )
list_1 = [ '张大仙' , 28 , "贫穷" , "乐观" , "勇敢" , ( '可乐' , '吃饭' , '厕所' ) ]
random. choice( list_1)
random. sample( list_1, 3 )
"""
补充:用于将一个列表中的元素打乱顺序,值得注意的是使用这个方法不会生成新的列表,只是将原列表的次序打乱
"""
list_2 = [ 1 , 3 , 5 , 7 , 9 ]
random. shuffle( list_2)
"""
random模块练习
"""
"""生成n(n>=4)位密码(要求由数字、大写字母、小写字母和符号组成)"""
def generate_password ( n= 4 ) :
if n < 4 :
raise "The parameter must be greater than or equal to 4"
list_3 = [ [ 33 , 47 ] , [ 48 , 57 ] , [ 65 , 90 ] , [ 97 , 122 ] ]
password = ""
for lt in list_3:
num = random. randint( lt[ 0 ] , lt[ - 1 ] + 1 )
password += chr ( num)
if n == 4 :
return password
for i in range ( 1 , n - 4 + 1 ) :
lt = random. choice( list_3)
num = random. randint( lt[ 0 ] , lt[ - 1 ] + 1 )
password += chr ( num)
password = list ( password)
random. shuffle( password)
password = "" . join( password)
return password
if __name__ == '__main__' :
print ( generate_password( 3 ) )
time 模块
hash 模块
'''
1 什么是哈希hash?
1.1 hash是一类算法,此算法接收传入的内容,通过运算得到一串的hash值(例如:md5、sha512、sha256)
1.2 hash值的特点:
1.2.1 只要传入的内容一样,得到的hash值必然相同
1.2.2 不能由hash值反解成内容
1.2.3 只要使用的hash算法不变,其hash长度是固定的
2 hash的用途
2.1 用途1:特点2可以用于密码密文传输与验证
2.2 用途2:特点1和3可以用于文件的完整性校验
3 如何使用
'''
''' 模拟撞库 '''
import hashlib
password_hash = 'a820194546ecff7d3f909876bdc53b37'
password_list = [ '123456' , '778899' , '1314520' , 'qwq789123' , 'cc56bb78' ]
dic = { }
for i in password_list:
m = hashlib. md5( )
m. update( i. encode( 'utf-8' ) )
hash_value = m. hexdigest( )
dic[ i] = hash_value
for v in dic:
if dic[ v] == password_hash:
print ( '撞库成功!密码原文>>>' , v)
break
else :
print ( '撞库失败!' )
''' 密码加盐 '''
re 模块
r'''左边的小r是为了防止转义"\"反斜杠
re模块 ~~~ 正则表达式
——————————————————————————————————————————
模式 ------------------ 描述
\w ------------------ 匹配字母数字及下划线
\W ------------------ 上面取反
\s ------------------ 匹配任意空白字符,等价于[\t\n\r\f]
\S ------------------ 上门取反
\d ------------------ 匹配任意数字
\D ------------------ 上面取反
\A ------------------ 以什么开头 [了解]
\Z ------------------ 以什么结尾(不能用在有换行地方) [了解]
^什么 ------------------ 以什么开头
什么$ ------------------ 以什么结尾
——————————————————————————————————————————
'''
import re
# 1 基本操作
# print(re.findall('\w', 'aAbc123_*()-='))
# print(re.findall('^love', 'love is my body, and I love it'))
# print(re.findall('love$', 'This is my love and The love is love'))
# 2 重复匹配
# 2.1 '.'匹配除了\n之外任意一个字符,指定re.DOTALL之后才能匹配换行
# print(re.findall('a.b', 'a1b a2b a b abbbb a\nb a\tb'))
# print(re.findall('a.b', 'a1b a2b a b abbbb a\nb a\tb', re.DOTALL))
# 2.2 '*'左边字符重复0次或以上,性格贪婪
# print(re.findall('ab*', 'a ab abb abbbbbb bbbbbbb'))
# 2.3 '+'左边字符重复1次或以上,性格贪婪
# print(re.findall('ab+', 'a ab abb abbbbb bbbbb '))
# 2.4 '?'左边字符重复0次或1次,性格贪婪
# print(re.findall('ab?', 'a ab abb bbbbb'))
# 2.5 '{n,m}'左边字符重复n次到m次,性格贪婪
# {0,} -> *
# {1,} -> +
# {0,1} -> ?
# {n} 单独一个n代表只出现n次
# print(re.findall('ab{2,5}','a ab abb abbb abbbb abbbbbbb bbbbbb'))
# 2.6 '[]'匹配指定字符一个
# print(re.findall('a[0-9]b', 'a11111b a3b a4b a9b aXb a b a\nb'))
# print(re.findall('a[0-9a-zA-Z]b', 'a11111b a3b a4b a9b aXb a b a\nb'))
# print(re.findall('a[^0-9a-zA-Z]b', 'a11111b a3b a4b a9b aXb a b a\nb'))
# print(re.findall('a[-0-9\n]b', 'a-b a11111b a3b a4b a9b aXb a b a\nb'))
# 3 小练习
# 3.1 匹配出所有的数字
# print(re.findall('\d+\.?\d*', 'asdfasdf123as1.13dfa12adsf1asdf3'))
shutil 模块
import shutil
shutil. copyfileobj( open ( 'old.xml' , 'r' ) , open ( 'new.xml' , 'w' ) )
shutil. copy( 'src' , 'dst' )
shutil. rmtree( 'folder1' )
shutil. move( 'folder1' , 'folder3' )
logging 模块
字典方式配置日志
文件名: settings.py
standard_format = '[ % ( asctime) s] [ % ( threadName) s: % ( thread) d] [ task_id: % ( name) s] ] \
[ % ( filename) s: % ( lineno) s] [ % ( levelname) s] - > % ( message) s'
simple_format = '[%(levelname)s] [%(asctime)s] [%(filename)s:%(lineno)d] [%(message)s]'
LOGGING_DIC = {
'version' : 1 ,
'disable_existing_loggers' : False ,
'loggers' : {
'pen1' : {
'level' : 'DEBUG' ,
'handlers' : [ 'console' ] ,
'propagate' : False
} ,
'pen2' : {
'level' : 'DEBUG' ,
'handlers' : [ 'default' ] ,
'propagate' : False
} ,
'' : {
'level' : 'DEBUG' ,
'handlers' : [ 'console' , 'default' ] ,
'propagate' : False
} ,
} ,
'handlers' : {
'console' : {
'level' : 'DEBUG' ,
'class' : 'logging.StreamHandler' ,
'formatter' : 'simple'
} ,
'default' : {
'level' : 'ERROR' ,
'class' : 'logging.handlers.RotatingFileHandler' ,
'formatter' : 'standard' ,
'filename' : 'test.log' ,
'encoding' : 'utf-8' ,
'maxBytes' : 1024 * 1024 * 5 ,
'backupCount' : 5
}
} ,
'formatters' : {
'standard' : {
'format' : standard_format
} ,
'simple' : {
'format' : simple_format
}
} ,
'filters' : { }
}
文件名: start.py
import logging. config
from settings import LOGGING_DIC
logging. config. dictConfig( LOGGING_DIC)
logger = logging. getLogger( '提现功能' )
logger. debug( '这是一条debug' )
logger. info( '这是一条info' )
logger. warning( '这是一条warning' )
logger. error( '这是一条error' )
logger. critical( '这是一条critical' )
编程式使用日志
文件名: log1
import logging
# # 输出程序运行的信息给维护人员看
# logging.debug('This is debug log')
# logging.info('This is info log')
# logging.warning('This is warning log')
# logging.error('This is error log')
# logging.critical('This is critical log')
# # 默认的日志输出级别为warning
# # 可使用baseConfig()来指定日志输出级别
# logging.basicConfig(level=logging.DEBUG)
# logging.debug('This is debug log')
# logging.info('This is info log')
# logging.warning('This is warning log')
# logging.error('This is error log')
# logging.critical('This is critical log')
文件名: log2
import logging
# 向文件输出日志 (文件的操作->默认是'a'模式, 可使用filemode='w'等等自行修改)
logging.basicConfig(filename='demo.log', filemode='a', level=logging.DEBUG)
logging.debug('This is debug log')
logging.info('This is info log')
logging.warning('This is warning log')
logging.error('This is error log')
logging.critical('This is critical log')
文件名: log3
import logging
# "绝对自定义"输出信息:format -> message
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
# 日志中的message部分:
name = 'peter'
age = '18'
logging.debug('姓名:%s, 年龄:%s, 充值失败' % (name, age))
文件名: log4
import logging
# 输出格式和添加一些公共信息
logging.basicConfig(format='%(asctime)s---%(levelname)s---%(filename)s---%(lineno)s---%(message)s',
datefmt='%Y-%m-%d %H:%M:%S', # 对上面的时间格式不满意,自定义后,再去覆盖原来提供给我们的时间格式
level=logging.DEBUG)
# 日志中的message部分:
name = 'peter'
age = '18'
logging.debug('姓名:%s, 年龄:%s, 充值失败' % (name, age))
logging.debug('姓名:%s, 年龄:%s, 充值失败' % (name, age))
logging.warning('姓名:%s, 年龄:%s, 充值失败' % (name, age))
文件名: log5
'''
# logging的高级应用
# 它提供给我们了四个类
Loggers: 记录器,提供应用程序代码能直接使用的接口
Handlers: 处理器,将记录器产生的日志发送到目的地
Filters: 过滤器,提供更好的粒度控制,决定哪些日志会被输出
Formatters: 格式化器,设置日志内容的组成结构和消息字段
'''
import logging
logger1 = logging. getLogger( 'applog' )
logger1. setLevel( logging. DEBUG)
consoleHandler = logging. StreamHandler( )
consoleHandler. setLevel( logging. DEBUG)
fileHandler = logging. FileHandler( filename= 'addDemo.log' )
fileHandler. setLevel( logging. CRITICAL)
fmt = logging. Formatter( '%(asctime)s|%(levelname)-8s|%(filename)10s:%(lineno)4s|%(message)s' )
consoleHandler. setFormatter( fmt)
fileHandler. setFormatter( fmt)
logger1. addHandler( consoleHandler)
logger1. addHandler( fileHandler)
flt = logging. Filter( 'cn.cccb' )
fileHandler. addFilter( flt)
logger1. debug( 'This is debug' )
logger1. info( 'This is info' )
logger1. warning( 'This is warning' )
logger1. error( 'This is error' )
logger1. critical( 'This is critical' )
配置文件式使用日志
文件名: loggg.conf
[ loggers]
keys= root, applog
[ handlers]
keys= fileHandler, consoleHandler
[ formatters]
keys= simpleFormatter
[ logger_root]
level= DEBUG
handlers= consoleHandler
[ logger_applog]
level= DEBUG
handlers= fileHandler, consoleHandler
qualname= applog
propagate= 0
[ handler_consoleHandler]
class = StreamHandler
args= ( sys. stdout, )
level= DEBUG
formatters= simpleFormatter
[ handler_fileHandler]
class = handlers. TimedRotatingFileHandler
args= ( 'applog.log' , 'midnight' , 1 , 0 )
level= DEBUG
formatters= simpleFormatter
[ formatter_simpleFormatter]
format = % ( asctime) s| % ( levelname) 8s| % ( filename) s[ : % ( lineno) d] | % ( message) s
datefmt= % Y- % m- % d % H: % M: % S
文件名: log11.py
# 配置文件的方式来处理日志
import logging
import logging.config
# 加载配置文件
logging.config.fileConfig('loggg.conf')
# 获取两个logger并使用即可
rootLogger = logging.getLogger()
rootLogger.debug('This is a root Logger, debug')
logger = logging.getLogger('applog')
logger.debug('This is applog, debug')
# 知识补充(绝对捕获异常):
a = 'abc'
try:
int(a)
except Exception as e:
# logger.error(e)
logger.exception(e)
subprocess 模块
''' 执行系统命令的模块 '''
import subprocess
# 创建一个对象,如果命令执行错误,结果走错误管道,反之
obj = subprocess.Popen('dir D:', shell=True, # 查看D盘下的内容, shell=True相当于调用了cmd
stdout=subprocess.PIPE, # 正确输出=管道
stderr=subprocess.PIPE, # 错误输出=管道
)
# 打印对象
print(obj)
# # 查看两个管道的结果
# print(obj.stdout.read()) # 正确输出的那条管道
# print(obj.stderr.read()) # 错误输出的那条管道
# 查看两个管道的结果
print(obj.stdout.read().decode('gbk')) # 正确输出的那条管道(跟着系统的编码进行信息解码)
print(obj.stderr.read().decode('gbk')) # 错误输出的那条管道(跟着系统的编码进行信息解码)
configparser 模块
'''
对配置文件进行操作的模块(configparser)
'''
import configparser
config = configparser.ConfigParser()
config.read('test.ini') # 获取配置文件的信息
# 获取sections
# print(config.sections())
# 获取某一sections下的所有options
# print(config.options('sections1'))
# 获取items
# print(config.items('sections1'))
# 获取具体的某个参数
# res = config.get('sections1', 'user')
# print(res, type(res))
# res = config.getint('sections1', 'age')
# print(res, type(res))
# res = config.getboolean('sections1', 'is_admin')
# print(res, type(res))