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等.但是我感觉自己都 ...
随机推荐
- MySQL 安装和启动服务,“本地计算机 上的 MySQL 服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止。”
MySQL 安装和启动服务,以及遇到的问题 MySQL版本: mysql-5.7.13-winx64.zip (免安装,解压放到程序文件夹即可,比如 C:\Program Files\mysql-5. ...
- js算出生日是当年第多少天
var year, month, day, monthSum = 0; var arr = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, ...
- C3属性的轮播图(持续更新)
天气好冷,都不想写代码.就先写个没有焦点的轮播图,过两天在补全. 用的是CSS3的属性 过渡transition 和 转换 transfrom:translateX() 只做了轮播和 鼠标进入停止轮播 ...
- 转发(forward)和重定向(sendRedirect)
一. RequestDispatche 是一个Web资源的包装器,可以用来把当前的Request传递给该资源,或者把新的资源包括到当前的相应中.详细来说:RequestDispatch对象从客户端获取 ...
- div水平垂直居中
我们平时常用的定高,top:50%:left:50%和margin-left负一半宽度margin-top负一半高度的居中方式暂不考虑,因为这种方式大家都会. 第一种绝对定位(absolute cen ...
- HTML DOM 方法
一.HMTL DOM对象 --方法和属性 1.1常用的方法. 1.getElementByld( id )方法 --获取带有指定id 的节点( 元素 ) 2.appendChild( node )方法 ...
- 类的static成员并用其实现一个单例模式
对于特定类型的全体对象而言,有时候可能需要访问一个全局的变量.比如说统计某种类型对象已创建的数量.如果我们用全局变量会破坏数据的封装,一般的用户代码都可以修改这个全局变量,这时我们可以用类的静态成员来 ...
- solr多词匹配搜索问题及解决
使用solr进行某较长词搜索时出现了一些问题,及解决方案. 1.问题:solr默认使用OR方式搜索,当搜索一个很长的次,比如“XX集团股份有限公司”,分词器分词后,使用OR方式匹配,会匹配到很多结果. ...
- rpm常用命令
* 手动安装 rpm 包 `rpm-ivh xxxxx.rpm` 参数: --force 即使覆盖其他包的文件也没强迫安装 --nodeps 即使依赖包没安装,也被强制安装 * 查看 rp ...
- Asp.Net MVC4入门指南(7):给电影表和模型添加新字段
在本节中,您将使用Entity Framework Code First来实现模型类上的操作.从而使得这些操作和变更,可以应用到数据库中. 默认情况下,就像您在之前的教程中所作的那样,使用 Entit ...