DAY18 常用模块(二)
一.随机数:RANDOM
1.(0,1)小数:random.random()
2.[1,10]整数:random.randint(1,10)
3.[1,10)整数:random.randrang(1,10)
4.(1,10)小数:random.uniform(1,10)
5.单列集合随机选择一个:random,choice(item)
6.单列集合随机选择n个:random.sample(item,n)
7.洗牌单列集合:random.shuffle(item)
1 import random 2 def random_code(count): 3 code = '' 4 for i in range(count): 5 num = random.randint(1, 3) 6 if num == 1: 7 tag = str(random.randint(0, 9)) 8 elif num == 2: 9 tag = chr(random.randint(65, 90)) 10 else: 11 tag = chr(random.randint(97, 122)) 12 code += tag 13 return code 14 print(random_code(6))
二.可以操作权限的处理文件模块
1.基于路径的文件复制:shutil.copyfile('原文件','新文件')
2.基于流的文件复制:
with open('source_file','rb') as r,
open('target_file','rb') as w
shutil.copyfileeobj(r,w)
3.递归删除目标目录
shutil.rmtree('target_folder')
4.文件移动:
shutile.remove('old_file','new_file')
5.文件夹压缩
shutil.make_archive('file_name','format','achive_path')
6.文件夹解压
shutil.unpack_archive('unpack_file','unpack_name','format')
三.可以用字典存取数据到文件的序列化模块:shevle
1.将序列化文件操作dump与load进行封装
s_dic = shelve.open("target_file", writeback=True) # 注:writeback允许序列化的可变类型,可以直接修改值
2.序列化::存
s_dic['key1'] = 'value1'
s_dic['key2'] = 'value2'
3.反序列化:取
print(s_dic['key1'])
4.文件释放
s_dic.close()
四.标准输入输出错误流
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