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等.但是我感觉自己都 ...
随机推荐
- lua 学习笔记一
参考: http://www.kancloud.cn/digest/luanote/119924 1.基础概念 1.lua八种基本数据类型:nil.boolean.string.function.ta ...
- linux 命令之comm
1. 简介 comm命令可以用于两个文件之间的比较,它有一些选项可以用来调整输出,以便执行交集.求差.以及差集操作. 交集:打印出两个文件所共有的行. 求差:打印出指定文件所包含的且不相同的行. 差集 ...
- inline(内联)函数
1,为小操作定义一个函数的好处是: a.可读性会强很多. b.改变一个局部化的实现比更改一个应用中的300个出现要容易得多 c.函数可以被重用,不必为其他的应用重写代码 ...
- 经典的找不到符号(symbol)错误 #iOS开发
使用BmobSDK的过程中,编译时出现了以下错误信息,意思是 -[BmobSRWebSocket _innerPumpScanner] 这个方法引用了 "_utf8_nextCharSafe ...
- Python3利用BeautifulSoup4批量抓取站点图片的代码
边学边写代码,记录下来.这段代码用于批量抓取主站下所有子网页中符合特定尺寸要求的的图片文件,支持中断. 原理很简单:使用BeautifulSoup4分析网页,获取网页<a/>和<im ...
- HTML 导航框架 (使用 Frame )
文章出处 : http://blog.sina.com.cn/s/blog_6f6d07f80100oqlt.html (本文转自此博客) 在浏览网页时,我们经常会看到一个导航条,当点击导航条上 ...
- jQuery Mobile 中创建按钮
在 jQuery Mobile 中创建按钮 jQuery Mobile 中的按钮可通过三种方法创建: 使用 <button> 元素 使用 <input> 元素 使用 data- ...
- ABAP POPUP函数
POPUP_TO_CONFIRM_LOSS_OF_DATA 弹出一个对话框告知用户有可能丢失数据,询问是否操作继续.POPUP_TO_CONFIRM_STEP 弹出一个对话框询问用户是否操作继续. P ...
- 使用WebDriver遇到的那些坑
在做web项目的自动化端到端测试时主要使用的是Selenium WebDriver来驱动浏览器.Selenium WebDriver的优点是支持的语言多,支持的浏览器多.主流的浏览器Chrome.Fi ...
- Hibernate QBC运算符
HQL运算符 QBC运算符 含义 = Restrictions.eq() 等于equal <> Restrictions.ne() 不等于not equal > Restrict ...