一、random:随机数
- 0, 1) 小数:random.random()
- [1, 10] 整数:random.randint(1, 10)
- [1, 10) 整数:random.randrange(1, 10)
- (1, 10) 小数:random.uniform(1, 10)
- 单例集合随机选择1个:random.choice(item)
- 单例集合随机选择n个:random.sample(item, n)
- 洗牌单列集合:random.shuffle(item)
# 产生指定位数的验证码
import random
def random_code(count):
code = ''
for i in range(count):
num = random.randint(1, 3)
if num == 1:
tag = str(random.randint(0, 9))
elif num == 2:
tag = chr(random.randint(65, 90))
else:
tag = chr(random.randint(97, 122))
code += tag
return code
print(random_code(6))
验证码案例
二、shutil:可以操作权限的处理文件模块
shutil.copyfile('source_file', 'target_file')
with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
shutil.copyfileobj(r, w)
shutil.rmtree('target_folder')
shutil.remove('old_file', 'new_file')
shutil.make_archive('file_name', 'format', 'archive_path')
shutil.unpack_archive('unpack_file', 'unpack_name', 'format')
三、shevle:可以用字典存取数据到文件的序列化模块
# 将序列化文件操作dump与load进行封装
s_dic = shelve.open("target_file", writeback=True) # 注:writeback允许序列化的可变类型,可以直接修改值
# 序列化::存
s_dic['key1'] = 'value1'
s_dic['key2'] = 'value2'
# 反序列化:取
print(s_dic['key1'])
# 文件这样的释放
s_dic.close()
四、三个流:标准输入流、输出流、错误流
import sys
sys.stdout.write('msg')
sys.stderr.write('msg')
msg = sys.stdin.readline()
# print默认是对sys.stdout.write('msg') + sys.stdout.write('
')的封装
# 格式化结束符print:print('msg', end='')
五、logging:日志模块
- root logging的基本使用:五个级别,打印级别是认为规定的
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.fatal('fatal')
logging.critical('critical')
- root logging的基本配置:logging.basicConfig()
- logging模块四个核心:Logger | Filter | Handler | Formater
- logging模块的配置与使用
- -- 配置文件:LOGGING_DIC = {}
- -- 加载配置文件:logging.config.dictConfig(LOGGING_DIC) => logging.getLogger('log_name')
import logging
import sys
handler1 = logging.FileHandler("owen.log", encoding="utf-8")
handler2 = logging.StreamHandler()
logging.basicConfig(
level=logging.DEBUG,
# stream=sys.stdout,
format='%(asctime)s -【%(levelname)s】: %(message)s',
# filename='owen.log'
handlers=[handler1, handler2]
)
# 打印级别是人为规定的
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.fatal('fatal')
logging.critical('critical')
View Code