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等.但是我感觉自己都 ...
随机推荐
- I/O流——其他流
其他流 一.ObjectInputStream/ObjectOutputStream ① ObjectInputStream和ObjectOutputStream分别与FileInputStream和 ...
- 【Android端 APP 启动时长获取】启动时长获取方案及具体实施
一.什么是启动时长? 1.启动时长一般包括三种场景,分别是:新装包的首次启动时长,冷启动时长.热启动时长 冷启动 和 热启动 : (1)冷启动:当启动应用时,后台没有该程序的进程,此时启动的话系统会分 ...
- iOS开发笔记之Runtime实用总结
前言 runtime的资料网上有很多了,部分有些晦涩难懂,我通过自己的学习方法总结一遍,主要讲一些常用的方法功能,以实用为主,我觉得用到印象才是最深刻的.另外runtime的知识还有很多,想要了解更多 ...
- 修改ubuntu中usr文件夹的权限后,sudo后出现sudo:must be setuid root问题的解决方案
无意之间,使用sudo chmod -R 777 /usr命令修改了usr文件的所有者,导致sudo:must be setuid root问题的出现,即sudo命令无法使用.网上介绍的方法差不多都相 ...
- 小记:Bmob云端代码测试APNS推送功能 #代码片段
function onRequest(request, response, modules) { var push = modules.oPush; push.send({ "data&qu ...
- JavaBean的toString方法工具类
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...
- 关于imagic拼接透明背景图片的问题
目标: 为了做图片水印,需要水平拼接多个logo和文字... 之前用过imagick,所以继续使用. 第一个版本:实现了图片和文字的拼接,代码如下: package main import ( &qu ...
- 学习Java,还需要学好哪些知识
很多人认为学好一门程序语言就需要学好逻辑,其实这对于很多人而言是对的,但是真的对于需要写程序的学员来说,只有逻辑好其实是不够的,如果你能具备以下几项能够为你在程序编译中大大提高工作效率.现在昆明jav ...
- Qt 程序访问 sqlite 权限错误
在Linux桌面上开发应用,想要拥有root权限,可是又需要弹窗申请.所以尽量避免这种情况发生. 另外:gksu,pkexec可以提供gui的root权限索取功能. 因为db文件是安装的时候放到etc ...
- (一)常用的CSS命名规则
头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar 栏目:column 页面外围控制整体布局宽度:wrapper 左右中:left rig ...