PYTHON学习之路_PYTHON基础(6)
学习内容:
Python模块介绍
1、time &datetime模块
2、random
3、shutil
4、shelve
5、xml处理
6、configparser
7、hashlib
8、logging模块
9、re正则表达式
一、time &datetime模块
print (time.time()/(3600*24*365)) #返回自1970年1月1日至今的秒数
print (time.altzone/(3600)) #返回与UTC时间的时间差
print (time.clock()) #
print (time.asctime()) # 返回时间 美国格式
print (time.ctime()) #返回时间 格式同上
print (time.gmtime()) #返回UTC时间的时间对象
print (time.localtime())#返回本地时间的时间对象
#字符串转成时间戳
t1=time.strptime('2016-11-11','%Y-%m-%d')
print ('T1-->',t1)
t1_tamp=time.mktime(t1)
print ('T1_tamp===>',t1_tamp)
#将时间戳转成字符串
t2=time.gmtime(t1_tamp+86400)
print ('T2',t2)
t2_tamp=time.strftime('%Y-%m-%d',t2)
print ('T2_tamp',t2_tamp)
print ('#------------------datetime----------------------')
print (datetime.datetime.now())
print (datetime.datetime.fromtimestamp(time.time()))
print (datetime.datetime.now() + datetime.timedelta(days=3)) #(cls, days=0, seconds=0, microseconds=0,
#milliseconds=0, minutes=0, hours=0, weeks=0):
now = datetime.datetime.now()
print (now.replace(month=1,day=3))
二、random
随机数模块
print (random.random()) #生成0到1之间的小数
print (random.randint(1,10)) #包含10
print (random.randrange(1,10)) #不包含10
print (random.sample(range(100),5)) #在前面一堆里选出随机选出5个字符
print (string.ascii_letters) #包含全部字符
print (string.digits) #包含全部数字
str_source = string.digits + string.ascii_letters #包含全部字母和数字
kkk=''.join(random.sample(str_source,6)) #生成随机数的方法
print (kkk)
check_code='' #生成随机数的方法
for i in range(6):
current_code=random.randint(0,6)
if current_code != i:
code=chr(random.randint(65,90))
else:
code=random.randint(0,9)
check_code += str(code)
print (check_code)
三、shutil
文件压缩模块
# shutil.copytree() #cp -rp tgz gztar tar 只打包 zip 压缩
# shutil.copyfileobj(fsrc, fdst[, length]) #将文件内容拷贝到另一个文件中,可以部分内容
# shutil.copyfile(src, dst) #拷贝文件
# shutil.copymode(src, dst) #仅拷贝权限。内容、组、用户均不变
# shutil.copystat(src, dst) #拷贝状态的信息,包括:mode bits, atime, mtime, flags
# shutil.copy(src, dst) #拷贝文件和权限
# shutil.copy2(src, dst) #拷贝文件和状态信息
# shutil.copytree(src, dst, symlinks=False, ignore=None) #递归的去拷贝文件 相当于cp -rp
# shutil.rmtree(path[, ignore_errors[, onerror]]) #递归的去删除文件
# shutil.move(src, dst) #递归的去移动文件
# shutil.make_archive(base_name, format,...) '''
# 创建压缩包并返回文件路径,例如:zip、tar
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的
四、shelve
文件持久化模块
正向:
d = shelve.open('shelve_test')
def sayHi(name,age):
print ('Hi %s,you are %s years old!'%(name,age))
info={'name':'alex','age':18,'sex':'F'}
name=['zhaoli','qiansan','lisi']
d['sayHi2']=sayHi
d['info2']=info
d['name2']=name
反向:
f=shelve.open('shelve_test')
def sayHi(name,age):
print ('Hi %s,you are %s years old!'%(name,age))
print (f['sayHi2']('alex',18))
print (f['info2']['sex'])
print (f['name2'])
五、xml处理
与json类似,是变量序列化的工具。python里对XML文件的增删改查。
import xml.etree.ElementTree as ET tree = ET.parse("xml_test")
root = tree.getroot()
print(root.tag) # 遍历xml文档
for child in root:
print(child.tag, child.attrib)
for i in child:
print('\t',i.tag, i.text) # 只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)
七、configparser
解析配置模块
import configparser config = configparser.ConfigParser()
#类似于数组
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
八、hashlib
文件安全和文件加密模块
import hashlib
m=hashlib.md5()
m.update(b'alex')
print (m.hexdigest())
m.update(b'li')
print (m.hexdigest()) m2 = hashlib.md5()
m2.update(b'alexli')
print (m.hexdigest()) hash = hashlib.sha1()
hash.update(b'alexli')
print ('SHA1',hash.hexdigest()) hash2 = hashlib.sha256()
hash2.update(b'alexli')
print ('SHA2',hash2.hexdigest()) hash5 = hashlib.sha512()
hash5.update(b'alexli')
print ('SHA5',hash5.hexdigest()) import hmac
hmaac_obj = hmac.new(b'salt',b'hello')
print ('HHHMAC:',hmaac_obj.hexdigest())
九、logging模块
记录日子模块
python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。
logging模块与log4j的机制是一样的,只是具体的实现细节不同。模块提供logger,handler,filter,formatter。
logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。
(1)通过logging.basicConfig函数对输出的日志格式进行配置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%d %b %Y %H:%M:%S %a',
filename='myapp.log',
filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
(2)将log同时输出到屏幕和文件
import logging # logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# datefmt='%d %b %Y %H:%M:%S',
# filename='myapp.log',
# filemode='w')
logger = logging.getLogger('calc')
logger.setLevel(logging.WARNING)
#################################################################################################
#定义一个StreamHandler
console = logging.StreamHandler('calc')
console.setLevel(logging.INFO)
#################################################################################################
#定义一个FileHandler
file_log = logging.FileHandler('myapp.log')
file_log.setLevel(logging.INFO)
#################################################################################################
#定义输出格式
formatter1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter2 = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
#################################################################################################
#将输出格式添加到标准输出中
console.setFormatter(formatter1)
file_log.setFormatter(formatter2)
#################################################################################################
#将输出格式绑定绑定到logger
logger.addHandler(file_log)
logger.addHandler(console) logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
十、re正则表达式
正则表达式模块
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.split 以匹配到的字符当做列表分隔符
re.sub 匹配字符并替换
'.'
默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^'
匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r
"^a"
,
"\nabc\neee"
,flags
=
re.MULTILINE)
'$'
匹配字符结尾,或e.search(
"foo$"
,
"bfoo\nsdfsf"
,flags
=
re.MULTILINE).group()也可以
'*'
匹配
*
号前的字符
0
次或多次,re.findall(
"ab*"
,
"cabb3abcbbac"
) 结果为[
'abb'
,
'ab'
,
'a'
]
'+'
匹配前一个字符
1
次或多次,re.findall(
"ab+"
,
"ab+cd+abb+bba"
) 结果[
'ab'
,
'abb'
]
'?'
匹配前一个字符
1
次或
0
次
'{m}'
匹配前一个字符m次
'{n,m}'
匹配前一个字符n到m次,re.findall(
"ab{1,3}"
,
"abb abc abbcbbb"
) 结果
'abb'
,
'ab'
,
'abb'
]
'|'
匹配|左或|右的字符,re.search(
"abc|ABC"
,
"ABCBabcCD"
).group() 结果
'ABC'
'(...)'
分组匹配,re.search(
"(abc){2}a(123|456)c"
,
"abcabca456c"
).group() 结果 abcabca456c
'\A'
只从字符开头匹配,re.search(
"\Aabc"
,
"alexabc"
) 是匹配不到的
'\Z'
匹配字符结尾,同$
'\d'
匹配数字
0
-
9
'\D'
匹配非数字
'\w'
匹配[A
-
Za
-
z0
-
9
]
'\W'
匹配非[A
-
Za
-
z0
-
9
]
's'
匹配空白字符、\t、\n、\r , re.search(
"\s+"
,
"ab\tc1\n3"
).group() 结果
'\t'
PYTHON学习之路_PYTHON基础(6)的更多相关文章
- PYTHON学习之路_PYTHON基础(1)
学习内容: 1.Python介绍 2.Python程序初接触和变量 3.Python用户交互 4.Python数据类型 5.Python循环if...(elif)...else 6.Python循环w ...
- PYTHON学习之路_PYTHON基础(10)
学习内容: Python进程与线程 1.线程及线程类 2.线程守护 3.线程等待 4.线程锁 5.信号量 6.timer用法 7.队列 8.事件驱动 9.生产者消费者模型 10.进程及进程同步 11. ...
- PYTHON学习之路_PYTHON基础(8)
学习内容: Python模块介绍 1.经典类 or 新式类 2.抽象接口 3.静态方法.类方法.属性方法 4.反射 5.异常处理 6.socket编程初识 7.用socket实现get.put文件等功 ...
- PYTHON学习之路_PYTHON基础(4)
学习内容: 1.Python函数的基本语法 2.Python函数的返回值与变量 3.Python嵌套函数 4.Python递归函数及实例(二分查找) 5.Python匿名函数 6.Python内置方法 ...
- PYTHON学习之路_PYTHON基础(3)
学习内容: 1.Python字典 2.Python集合 3.Python字符编码 4.Python文件操作 5.Python实例 一.Python字典 1.定义: dic1={'name':'alex ...
- PYTHON学习之路_PYTHON基础(2)
学习内容: 1.Python数据类型与变量 2.Python字符串 3.Python列表 4.Python while循环 5.Python字典 6.Python实例 一.Python数据类型与变量 ...
- python学习之路-day2-pyth基础2
一. 模块初识 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,第三方库存放位置:site-packages sys模块简介 导入模块 import sys 3 sys模 ...
- Python学习之路-Day2-Python基础2
Python学习之路第二天 学习内容: 1.模块初识 2.pyc是什么 3.python数据类型 4.数据运算 5.bytes/str之别 6.列表 7.元组 8.字典 9.字符串常用操作 1.模块初 ...
- Python学习之路-Day1-Python基础
学习python的过程: 在茫茫的编程语言中我选择了python,因为感觉python很强大,能用到很多领域.我自己也学过一些编程语言,比如:C,java,php,html,css等.但是我感觉自己都 ...
随机推荐
- 转载 --ios 模型-setValuesForKeysWithDictionary
应用场景:app请求后端数据,返回的数据是JSON形式,如: { "is_favor" = 0; "is_follow" = 0; "is_prais ...
- 2 Add Two Numbers
// Java public ListNode addTwoNumbers(ListNode l1, ListNode l2) { return add(l1, l2, false); } priva ...
- Activity之间传递参数(二)
------siwuxie095 传递数据包 1.传递数据包要用到Bundle,MainActivity.java中: package com.siwuxie095.sendargs; import ...
- 防止多次领取红包进行ID锁
//controller里面使用锁 ActivityRedPacket ap = customerService.getActivityRedPacket(params); if (synchr ...
- js中常用的操作
1.js中常用的数组操作 2.js中常用的字符串操作 3.js中常用的时间日期操作 4.定时器
- MAVEN解决Cannot change version of project facet Dynamic web module to 2.5
我们用Eclipse创建Maven结构的web项目的时候选择了Artifact Id为maven-artchetype-webapp,由于这个catalog比较老,用的servlet还是2.3的,而一 ...
- PTGM and APTM
1. 性能测试过程模型(PTGM) PTGM模型包括以下几个步骤: 测试前期的准备 测试工具的引入 测试计划 测试设计与开发 测试执行与管理 测试分析 测试前期准备:主要任务为保证系统稳定和建立合适的 ...
- win7+vs2010+opencv2.4.6配置
记录一下配置,省的以后还到处去找: (一) 添加环境变量://第一次使用opencv的话需要加环境变量:” %opencv%\build\x86\vc10\bin”和”%opencv%\build\c ...
- 远程debug hadoop
- 搭建高可用mongodb集群(三)—— 深入副本集内部机制
在上一篇文章<搭建高可用mongodb集群(二)—— 副本集> 介绍了副本集的配置,这篇文章深入研究一下副本集的内部机制.还是带着副本集的问题来看吧! 副本集故障转移,主节点是如何选举的? ...