python's twenty-sixth day for me 模块
configparser 模块:
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键 = 值)。
创建文件:
# 创建文件
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'SeverAliveInterval':'',
'Compression':'yes',
'CompressionLevel':'',
'ForwardXll':'yes'
}
config['bitbucket.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'','ForwardXll':'no'}
with open('example.ini','w') as configfile:
config.write(configfile)
查找文件:
# 查找文件
import configparser
config = configparser.ConfigParser()
# 查找文件内容,基于字典的形式。
print(config.sections()) # [] 如果没有指定文件路径,则打印的就是空列表
config.read('example.ini')
print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] 除了DEFAULT的所有小节名
print('bytebong.com' in config) # False 查询小节名,存在返回True不存在则返回Falese
print('bitbucket.org' in config) # True
print(config['bitbucket.org']['user']) # hg
print(config['DEFAULT']['compression']) # yes
print(config['topsecret.server.com']['ForwardXll']) # no
print(config['bitbucket.org']) # <Section: bitbucket.org> 打印对象名[小节名] 相当于返回一个迭代器
for i in config['bitbucket.org']:
print(i) # 将文件中指定小节的键打印出来,若是有DEFAULT则会将DEFAULT的键默认打印出来。
# user
# severaliveinterval
# compressionlevel
# forwardxll
# forwardxll
print(config.options('bitbucket.org')) # ['user', 'forwardxll', 'compression', 'severaliveinterval', 'compressionlevel']
# 将 小节名下的键以列表形式打印出来,若是有default则将default中的键也添加到列表中。
print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value
增删改操作:把文件内容取出来更改所以要写入一个新文件中,才能更改。
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan') config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com','forwardXll') config.set('topsecret.server.com','k1','')
config.set('yuan','k2','')
config.write(open('new2.ini','w')) # 新建一个文件,把更改后的文件写入。
logging 模块:
1,记录日志的模块。
2,它不能自己打印内容,只能根据程序员写的代码来完成功能。
3,logging模块提供五种日志级别从低到高排序:debug , info , warning , error , critical
4,只显示一些基础信息,可以对显示的格式做一些配置。
函数式简单配置:
# 函数式见配置
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message') # WARNING:root:warning message
# ERROR:root:error message
# CRITICAL:root:critical message
# 默认打印warning级别以上的所有日志。
# 日志级别:criticla > error > warning > info> debug
灵活配置日志级别,日志格式,输出位置:
import logging
# 默认情况下 只显示 警告 及警告级别以上信息
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %y %H:%M:%S',
filename = 'userinfo.log'
)
logging.debug('debug message') # debug 调试模式 级别最低
logging.info('info message') # info 显示正常信息
logging.warning('warning message') # warning 显示警告信息
logging.error('error message') # error 显示错误信息
logging.critical('critical message') # 缺点:编码格式不能设置。
# 不能同时输出到文件和屏幕。
logger对象配置:
import logging
# logging.basicConfig(level = logging.DEBUG)
logger = logging.getLogger()
fh = logging.FileHandler('log',encoding='utf-8') # 创建一个handler,用于写入日志文件。
ch = logging.StreamHandler() # 创建一个handler,用于输出控制台
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setLevel(level=logging.DEBUG) # 对文件句柄设置等级。 fh.setFormatter(formatter) # 格式和文件句柄或者屏幕句柄关联
ch.setFormatter(formatter)
logger.addHandler(fh) # logger对象可以添加多个fh和ch对象,和logger(对象)关联的只有句柄。
logger.addHandler(ch) logging.debug('debug message') # debug 调试模式 级别最低
logging.info('info message') # info 显示正常信息
logging.warning('warning message') # warning 显示警告信息
logging.error('error message') # error 显示错误信息
logging.critical('critical message')
配置参数:
logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有: filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
配置参数
collections 模块:
namedtuple:
from collections import namedtuple
Point = namedtuple('Point',['x','y'])
p = Point(1,2)
print(p.x) #
print(p.y) #
deque:
from collections import deque
# 双端队列
dq = deque()
dq.append(1) # 默认依次往右添加。
dq.append(2)
dq.append(3)
print(dq) # deque([1, 2, 3]) 类似于列表,但不是列表。
print(dq.pop()) # 3 默认删除最后一个添加进去的。
print(dq.popleft()) # 从左侧开始删除。
dq.appendleft(4) # 从左侧添加
dq.appendleft(5)
print(dq) # deque([5, 4, 2])
OrderedDict:
from collections import OrderedDict
dic = OrderedDict([['k1','v1'],['k3','v3'],['k2','v2']])
print(dic) # OrderedDict([('k1', 'v1'), ('k3', 'v1'), ('k2', 'v1')])
dic = OrderedDict([('k1','v1'),('k2','v2'),('k3','v3')])
print(dic) # OrderedDic #子元素是列表或者元素都可以!
defaultdict:
from collections import defaultdict d = defaultdict(list)
print(d) # defaultdict(<class 'list'>, {})
l = [11,22,33,44,55,66,77,88,99]
for i in l:
if i>66:
d['k1'].append(i)
elif i<66:
d['k2'].append(i)
print(d) # defaultdict(<class 'list'>, {'k1': [77, 88, 99], 'k2': [11, 22, 33, 44, 55]})
# 默认字典最大的好处就是,永远不会再你使用key获取值的时候报错。
# 默认字典 是给 字典中的 value设置默认值。
Counter:
from collections import Counter
c = Counter('sdfsafsdfsa')
print(c) # Counter({'s': 4, 'f': 3, 'a': 2, 'd': 2})
# 可以计算字符串每个元素出现的次数,并按次数从大到小排序
python's twenty-sixth day for me 模块的更多相关文章
- python's twenty eithth day for me 模块和包
模块: 什么是模块: 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀,但其实import加载的模块分为四个通用类别: 1,使用python编写的代码 ...
- Windows下用Python 3.4+自带的venv模块创建虚拟环境
Python 3.4+自带了venv模块,用于创建虚拟环境,每个虚拟环境都可以安装一套独立的第三方模块. 本文在Windows 10上操作. 1.创建一个虚拟环境: D:\>mkdir test ...
- python【第五篇】常用模块学习
一.主要内容 模块介绍 time &datetime模块 random os sys shutil json & pickle shelve xml处理 yaml处理 configpa ...
- Python自动化运维之10、模块之json、pickle、XML、PyYAML、configparser、shutil
序列化 Python中用于序列化的两个模块 json 用于[字符串]和 [python基本数据类型] 间进行转换 pickle 用于[python特有的类型] 和 [python基本数据类 ...
- Python学习笔记4(函数与模块)
1.Python程序的结构 Python的程序由包(package).模块(module)和函数组成. 模块是处理一类问题的集合,由函数和类组成. 包是由一系列模块组成的集合.包是一个完成特定任务的工 ...
- python之路第五篇之模块和加密算法(进阶篇:续)
模块 Python中,如果要引用一些内置的函数,该怎么处理呢?在Python中有一个概念叫做模块(module) 简单地说,模块就是一个保存了Python代码的文件. 模块分类: 1)内置模块 2)自 ...
- Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式
Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式 目录 Pycharm使用技巧(转载) Python第一天 安装 shell 文件 Py ...
- Python 学习 第十五篇:模块搜索路径和包导入
在导入自定义的模块时,除了指定模块名之外,也需要指定目录,由于Python把目录称作包,因此,这类导入被称为包导入.包导入把计算机上的目录变成Python的命名空间,而目录中所包含的子目录和模块文件则 ...
- python文件、文件夹操作OS模块
转自:python文件.文件夹操作OS模块 '''一.python中对文件.文件夹操作时经常用到的os模块和shutil模块常用方法.1.得到当前工作目录,即当前Python脚本工作的目录路径: ...
- Python进阶【第十一篇】模块(下)之常用模块
内置模块是Python自带的功能,在使用内置模块相应的功能时,需要[先导入]再[使用] 一.time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳 ...
随机推荐
- shiro源码解析--------欢迎指出错误地方,还有一起讨论一下ShiroFilterFactoryBean配置过滤URL规则
啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 啦啦啦啦啦 ...
- ionic2常见问题——启动后白屏问题
问题描述 app启动后大概有几秒白屏,才会显示首页. 解决方案 图 1-最初config.xml配置 图 2-更改后的splash配置 代码: <preference name="Sh ...
- L141
nest egg留窝鸡蛋,养老金,储备金first base一垒的位置, <俚>跨出第一步not hold a candle to不能与 ... 相比; 比不上a bone of cont ...
- JQuery动态隐藏和显示DIV
<head> <script language="javascript"> function HideWeekMonth() { $("#tt1& ...
- Arcgis For Android之离线地图实现的几种方式
为什么要用,我想离线地图的好处是不言而喻的,所以很多人做系统的时候都会考虑用离线地图.在此,我给大家介绍几种Arcgis For Android下加载离线地图的方式. 在Arcgis For Andr ...
- As3 Practises : use TheMiner do as3 project swf performance profile , find memory leak!
The second and most universal way is to launch it from the mm.cfg fileTheMiner.swf must be trusted1: ...
- hibernate的注解属性mappedBy详解【实际项目】
[应用情节: 技术问答] 一个类是问题类 一个类是回答类 一个类是针对回答的讨论类 关系是一个问题对应多个答案 一个答案对应多个讨论 [三个类的注解关系] 问题类的 答案类的 讨论类的
- bzoj 2657 旅游
Written with StackEdit. Description 到了难得的暑假,为了庆祝小白在数学考试中取得的优异成绩,小蓝决定带小白出去旅游~~ 经过一番抉择,两人决定将\(T\)国作为他们 ...
- Quartz 2D编程指南(1) - 概览
Quartz 2D编程指南是论坛会员德鲁伊翻译的国外的Quartz 2D一系列学习资料,供大家参考 Quartz 2D是一个二维图形绘制引擎,支持iOS环境和Mac OS X环境.我们可以使用Quar ...
- HDFS的工作原理扫扫盲
问题导读: 1.什么是分布式文件系统? 2.怎样分离元数据和数据? 3.HDFS的原理是什么? Hadoop分布式文件系统(HDFS)是一种被设计成适合运行在通用硬件上的分布式文件系统.HDFS是一个 ...