常用模块二

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('\n')的封装
# 格式化结束符print:print('msg', end='')

logging:日志模块

'''
1) root logging的基本使用:五个级别
2)root logging的基本配置:logging.basicConfig()
3)logging模块四个核心:Logger | Filter | Handler | Formater
4)logging模块的配置与使用
	-- 配置文件:LOGGING_DIC = {}
	-- 加载配置文件:logging.config.dictConfig(LOGGING_DIC) => logging.getLogger('log_name')
'''
posted @ 2019-05-29 23:18  西西灬弗斯  阅读(87)  评论(0编辑  收藏  举报