DAY18、常用模块

一、random:随机数
1、(0,1) 小数:random.random()
2、[1,10] 整数:random.randint(1,10)
3、[1,10) 整数:random.randrange(1,10)
4、(1,10) 小数:random.uniform(1,10)
5、单列集合随机选择1个:random.choice(item)
6、单列集合随机选择n个:random.sample(item,n)
7、洗牌单列集合:raandom.shuffle(item)
8、例:
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.count)

二、shutil:可以操作权限的处理文件模块
1、基于路径的文件复制:shutil.copyfile('source_file','target_file') #两个路径
2、基于流的文件复制:with open('source_file','rb')as r,open('target_file','wb')as w:
shutil.copyfileobj(r,w)
3、递归删除目标目录:shutil.rmtree()
4、文件移动:shutil.move('a/aa.py','b/bb.py')
5、文件夹压缩:shutil.make_archive(目标文件,'zip',存放路径)
6、文件夹解压:shutil.unpack_archive(目标文件,存放路径,'方式(看格式)('zip','gztar')')

三、shevle:可以用字典存取数据到文件的序列化模块
将序列化文件操作dump与load进行封装
s_dic = shelve.open('target.txt') #注:writeback=True操作数据会同步写到文件
1、序列化:存
s_dic['key1'] = [1,2,3,4,5]
s_dic['key2'] = {'name':'Bob','age':18}
  s_dic['key2'] = 'abc'
  s_dic.close()
2、反序列化:取
  s_dic = shelve.open("target.txt", writeback=True)
  print(s_dic['key1'])
  s_dic['key1'][2] = 30
  print(s_dic['key1'])

  print(s_dic['key2'])
  s_dic['key2']['age'] = 300
  print(s_dic['key2'])

  print(s_dic['key3'])
  s_dic['key3'] = 'def'
  print(s_dic['key3'])
  s_dic.close()

四、标准输入输出错误流
1、sys.stdout.write('msg') #print('msg',end='')
2、sys.stderr.write('msg')
3、msg = sys.stdin.readline()

五、logging:日志模块
1、root logging的基本使用:五个级别
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.fatal('fatal')
logging.critical('critical')
2、root logging的基本配置:
logging.basicConfig(
level=logging.DEBUG,
#stream=logging.stdout,
format='%(asctime)s-[%(levelname)s]:%(message)s',
#filename='owen.log',
handlers=[handler1,handler2]
)
3、logging模块四个核心:
Logger | Filter | Handler | Formater
#规定输出源
handler1 = logging.FileHandler('owen.log',enconding='utf-8')
handler2 = logging.StreamHandler()
#规定输出格式
fmt = logging.Formatter(
fmt='%(asctime)s-%(name)s-%(levelname)s:%(message)s',
datefmt='%m-%d %H:%M:%S %p)'
4、logging模块的配置与使用
配置文件:LOGGING_DIC = {}
加载配置文件:
logging.config.dictConfig(LOGGING_DIC)
logging.getLogger('log_name')

猜你喜欢

转载自www.cnblogs.com/yanminggang/p/10691906.html