Python—day18 dandom、shutil、shelve、系统标准流、logging
一、dandom模块
(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)
import random
# print(random.random())
# print(random.randint(1, 10))
# print(random.randrange(1, 10))
# print(random.uniform(1, 10)) print(random.choice('abc'))
print(random.sample({1,2,3,4,5},3)) # 输出结果:以列表形式输出[1, 3, 4] ls=[1,2,3,4,5]
random.shuffle(ls)
print(ls)
案例:设计验证码
def random_code(count):
code=''
for i in range(count):
num=random.choice([1,2,3])
if num==1: # 自己设置 可以设置为数字
code+=str(random.randint(0,9)) # 转成字符串,通过列表一个一个传然后在转成字符串输出
elif num==2: # 可以设置为大写字母
code+=chr(random.randint(65,90)) #通过ASCII码查找大写字母
else:
code += chr(random.randint(97, 122)) #通过ASCII码查找小写字母
return code
print(random_code(6)) # 简化版: def random_code1(count):
source='ABCDEFabcdef0123456789'
code_list=random.sample(source,count)
return ''.join(code_list)
print(random_code1(6))
二、shutil模块
import shutil # 1、 基于路径的文件复制:
shutil.copyfile('source_file', 'target_file') # 2、 基于流的文件复制:
with open('a.py', 'rb') as r, open('b.py', 'wb') as w:
shutil.copyfileobj(r, w) #3、 递归删除目标目录
shutil.rmtree('target_folder') # 4、文件移动
shutil.move('a/a.py', 'b/a.py')# 可以从文件夹移动到另一个文件夹
shutil.move('a/a.py', 'b/b.py') # 可以从文件夹移动到另一个文件夹并可以移动时重命名 # 5、文件夹压缩
shutil.make_archive('file_name', 'format', 'archive_path')
# 不写路径地址,会将当前根目录文件夹下所有目录压缩 gztar、zip两种压缩解压缩方式 # 6、文件夹解压
shutil.unpack_archive('archive_path:解压的文件路径', 'file_name:解压到的文件名', 'format:解压方式')
三、shelve模块
# 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 shelve # 将序列化文件操作dump与load进行封装
s_dic=shelve.open('t.txt') # writeback=True 时操作的数据会同步写到文件中 # 序列化:存
s_dic['key1']=[1,2,3,4,5]
s_dic['key2']={'name':'abc','age':18}
s_dic['key3']='abc'
s_dic.close() # 文件释放
#
s_dic=shelve.open('t.txt',writeback=True)
print(s_dic['key1'])
s_dic['key1'][2]=30 # 将key1中的第三个数改为30
print(s_dic['key1']) # 输出结果:[1, 2, 3, 4, 5] [1, 2, 30, 4, 5] print(s_dic['key2'])
s_dic['key2']['age']=300 # 将key2中的age数改为300
print(s_dic['key2']) # 输出结果:{'name': 'abc', 'age': 18} {'name': 'abc', 'age': 300} print(s_dic['key3'])
s_dic['key3']='defg' # 将key3将abc改为defg的几个字符串
print(s_dic['key3'])
s_dic.close() from shelve import DbfilenameShelf
res=shelve.open('t.txt')
print(res,type(res))
#输出结果: shelve.DbfilenameShelf object at 0x00000247CD0EB320> <class 'shelve.DbfilenameShelf'>
四、系统标准流(流入、流出、信息错误流)
# 指:系统标准输入流|输出流|错误流 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='')
# 1、标准输出流
import sys
sys.stdout.write('') # 相当于print('msg',end=)
sys.stdout.write('123\n') # 相当于==print() print('abc',end='')
# 输出结果123123
# abc
print('abc',end='')
# 输出结果 123123
# abcabc # 2、 标准错误流
sys.stderr.write('错误信息\n')
sys.stderr.write('错误信息')
sys.stderr.write('错误信息')
#输出结果: 错误信息 (第一个换行了,所以到第二行才显示)
# 错误信息错误信息 # 3、系统标准输入流
res=sys.stdin.read(3)
print(res) # 输出的结果:不管输入多少输出都被限制为3位
res=sys.stdin.readline()
print(res) # 输出的结果:输入多行就输出多行,如加上上面的限制,则输出的一行变为多行,每行个数为3
五、logging模块
# logging 的日志可以分为debug()、info()、warning()、error()、critical() 5个级别 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')
import logging
import sys handler1=logging.FileHandler("a.log",encoding='utf-8')
handler2=logging.StreamHandler() logging.basicConfig(
level = logging.DEBUG,
# stream=sys.stdout, # 将打印出的红字变成白色的字
format="%(asctime)s -【%(level name)s】:%(massage)s",
# filename='a.log',
handlers=[handler1,handler2]) # 打印级别是人为规定的(现只能打印出最后三个。前两个级别比较低无法打印出来)
logging.debug('debug')
logging.info('info')
# logging.warning('warning')
# logging.error('error')
# logging.fatal('fatal') # ==logging.critical('critical')
import logging # 规定输出源
handler1 = logging.FileHandler("a.log", encoding="utf-8")
handler2 = logging.StreamHandler() # 规定输出格式
fmt=logging.Formatter(
fmt="%(asctime)s-%(name)s-%(levelname)s:%(message)s",
datefmt="%m-%d %H:%M:%S %p") o_log=logging.getLogger('abc')
o_log.setLevel(10) # 给logger设置打印级别
o_log.addHandler(handler1) #设置输出源,可以多个
o_log.addHandler(handler2)
handler1.setFormatter(fmt) # 设置输出格式
o_log.warning('abc message') o_log1=logging.getLogger('zxc')
o_log1.setLevel(10)
o_log1.addHandler(handler2)
handler2.setFormatter(fmt)
o_log1.warning('zxc message')
Python—day18 dandom、shutil、shelve、系统标准流、logging的更多相关文章
- python基础——14(shelve/shutil/random/logging模块/标准流)
一.标准流 1.1.标准输入流 res = sys.stdin.read(3) 可以设置读取的字节数 print(res) res = sys.stdin.readline() print(res) ...
- Python 第五篇(下):系统标准模块(shutil、logging、shelve、configparser、subprocess、xml、yaml、自定义模块)
目录: shutil logging模块 shelve configparser subprocess xml处理 yaml处理 自定义模块 一,系统标准模块: 1.shutil:是一种高层次的文件操 ...
- Python 第五篇(上):算法、自定义模块、系统标准模块(time 、datetime 、random 、OS 、sys 、hashlib 、json和pickle)
一:算法回顾: 冒泡算法,也叫冒泡排序,其特点如下: 1.比较相邻的元素.如果第一个比第二个大,就交换他们两个. 2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对.在这一点,最后的元素应 ...
- python 全栈开发,Day48(标准文档流,块级元素和行内元素,浮动,margin的用法,文本属性和字体属性)
昨日内容回顾 高级选择器: 后代选择 : div p 子代选择器 : div>p 并集选择器: div,p 交集选择器: div.active 属性选择器: [属性~='属性值'] 伪类选择器 ...
- python学习之算法、自定义模块、系统标准模块(上)
算法.自定义模块.系统标准模块(time .datetime .random .OS .sys .hashlib .json和pickle) 一:算法回顾: 冒泡算法,也叫冒泡排序,其特点如下: 1. ...
- python基础系列教程——Python3.x标准模块库目录
python基础系列教程——Python3.x标准模块库目录 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata ...
- python ConfigParser、shutil、subprocess、ElementTree模块简解
ConfigParser 模块 一.ConfigParser简介ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号“[ ]”内包含的为section.section 下面为类 ...
- Python标准模块--logging
1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...
- 数据分析:基于Python的自定义文件格式转换系统
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
随机推荐
- Entitas Learning Document
Entitas Learning Document You can find Entitas project in there Entitas for Unity Github There are a ...
- XYZZY spfa 最长路 判环
题意: 有n个点 m条边 每个边有权值 一开始有一百血 每次经过一条路都会加上其权值 判断是否能够到达n 显然 有正环的时候肯定能够到达 最短路好题!!!!!!! 显用folyed判断是否联通 ...
- CentOS7完成mysql的安装和远程访问
详见链接https://blog.csdn.net/weixin_42266606/article/details/80879571 (此处我的本地用户名root,密码root:远程用户名root,密 ...
- CodeForces 510C Fox And Names (拓扑排序)
<题目链接> 题目大意: 给你一些只由小写字母组成的字符串,现在按一定顺序给出这些字符串,问你怎样从重排字典序,使得这些字符串按字典序排序后的顺序如题目所给的顺序相同. 解题分析:本题想到 ...
- vue插件官方文档,做个记录
vue的插件,组件都可以按照这种方式添加 官方文档 https://cn.vuejs.org/v2/guide/plugins.html 做个记录用
- JQuery模拟常见的拖拽验证
css部分 <style> #drag{ position: relative; background-color: #e8e8e8; width: 300px; height: 34px ...
- 13-事务&数据库连接池&DBUtiles
事务&数据库连接池&DBUtils 事务 Transaction 其实指的一组操作,里面包含许多个单一的逻辑.只要有一个逻辑没有执行成功,那么都算失败. 所有的数据都回归到最初的状态 ...
- Jenkins pipeline job 根据参数动态获取触发事件的分支
此文需要有Jenkins pipeline job 的简单使用经验 场景 我们日常的测试函数, 一般是不能仅仅在本地跑的,还需要一个公共的跑测试的环境,作为合并新的PR的依据. 如果用Jenkins ...
- 详解Session和cookie
1.cookie 1.1. 为什么会有cookie? 由于HTTP是无状态的,服务端并不记得你之前的状态.这种设计是为了HTTP协议的方便,但是也存在一些问题.比如我们登录一个购物网站,我们需要用户登 ...
- Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
提示哪个引用修改哪个引用的属性: Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, ...