Python基础-5

摘要:
目录时间和日期时间模块randomossysshutiljson&picleshelvexml处理yaml处理hashlibre正则表达式模块分为三种类型:自定义模块内置标准模块(也称为标准库)开源模块使用自定义模块和开源模块的引用http://www.cnblogs.com/wupeiqi/articles/4963027.html1、时间和日期时间模块1重要时间2

目录

  1. time &datetime模块
  2. random
  3. os
  4. sys
  5. shutil
  6. json & picle
  7. shelve
  8. xml处理
  9. yaml处理
  10. hashlib
  11. re正则表达式

模块分为三种:

  • 自定义模块
  • 内置标准模块(又称标准库)
  • 开源模块

自定义模块 和开源模块的使用参考 http://www.cnblogs.com/wupeiqi/articles/4963027.html 

一、time & datetime模块

 1 import time
 2 
 3 
 4 print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
 5 1.2828758313035386e-06
 6 print(time.altzone)  #返回与utc时间的时间差,以秒计算
 7 -32400
 8 print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
 9 Wed Jun 28 23:09:48 2017
10 print(time.localtime()) #返回本地时间 的struct time对象格式
11 time.struct_time(tm_year=2017, tm_mon=6, tm_mday=28, tm_hour=23, tm_min=9, tm_sec=48, tm_wday=2, tm_yday=179, tm_isdst=0)
12 print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
13 time.struct_time(tm_year=2017, tm_mon=6, tm_mday=28, tm_hour=23, tm_min=9, tm_sec=48, tm_wday=2, tm_yday=179, tm_isdst=0)
14 print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
15 Wed Jun 28 23:09:48 2017
16 print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
17 Wed Jun 28 23:09:48 2017
18 
19 
20 # 日期字符串 转成  时间戳
21 string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
22 print(string_2_struct)
23 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1)
24 
25 struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
26 print(struct_2_stamp)
27 1463846400.0
28 
29 
30 #将时间戳转为字符串格式
31 print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
32 time.struct_time(tm_year=2017, tm_mon=6, tm_mday=27, tm_hour=15, tm_min=5, tm_sec=48, tm_wday=1, tm_yday=178, tm_isdst=0)
33 
34 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
35 2017-06-28 15:09:48
36 
37 
38 #时间加减
39 import datetime
40 
41 print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
42 2017-06-28 23:14:57.032901
43 print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
44 2017-06-28
45 print(datetime.datetime.now() )
46 2017-06-28 23:14:57.032901
47 print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
48 2017-06-28 23:14:57.032901
49 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
50 2017-06-28 23:14:57.032901
51 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
52 2017-06-29 02:14:57.032901
53 print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
54 2017-06-28 23:44:57.032901
55 
56 c_time  = datetime.datetime.now()
57 print(c_time.replace(minute=3,hour=2)) #时间替换
58 2017-06-28 02:03:57.032901
DirectiveMeaningNotes
%aLocale’s abbreviated weekday name. 
%ALocale’s full weekday name. 
%bLocale’s abbreviated month name. 
%BLocale’s full month name. 
%cLocale’s appropriate date and time representation. 
%dDay of the month as a decimal number [01,31]. 
%HHour (24-hour clock) as a decimal number [00,23]. 
%IHour (12-hour clock) as a decimal number [01,12]. 
%jDay of the year as a decimal number [001,366]. 
%mMonth as a decimal number [01,12]. 
%MMinute as a decimal number [00,59]. 
%pLocale’s equivalent of either AM or PM.(1)
%SSecond as a decimal number [00,61].(2)
%UWeek number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.(3)
%wWeekday as a decimal number [0(Sunday),6]. 
%WWeek number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.(3)
%xLocale’s appropriate date representation. 
%XLocale’s appropriate time representation. 
%yYear without century as a decimal number [00,99]. 
%YYear with century as a decimal number. 
%zTime zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. 
%ZTime zone name (no characters if no time zone exists). 
%%A literal '%' character.

Python基础-5第1张

二、random模块

随机数

1 import random
2 print(random.random()) #生成[0,1)
3 print(random.randint(1,4)) #生成随机1,2,3,4
4 print(random.randrange(1,10)) #生成随机1到9的整数,random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效

random.choice

random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。.

random.shuffle

random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱.

 1 import random
 2 
 3 list = [20, 16, 10, 5]
 4 random.shuffle(list)
 5 print("随机排序列表 : ",  list)
 6 
 7 random.shuffle(list)
 8 print("随机排序列表 : ",  list)
 9 
10 结果:
11 随机排序列表 :  [5, 20, 10, 16]
12 随机排序列表 :  [5, 16, 20, 10]

random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

1 import random
2 s = random.sample('abcdefghij',3)
3 print(s)
4 
5 随机选取三个元素
6 ['f', 'h', 'd']

三、OS模块

提供对操作系统进行调用的接口

 1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
 3 os.curdir  返回当前目录: ('.')
 4 os.pardir  获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dirname1/dirname2')    可生成多层递归目录
 6 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 9 os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove()  删除一个文件
11 os.rename("oldname","newname")  重命名文件/目录
12 os.stat('path/filename')  获取文件/目录信息
13 os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
14 os.linesep    输出当前平台使用的行终止符,win下为"	
",Linux下为"
"
15 os.pathsep    输出用于分割文件路径的字符串
16 os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")  运行shell命令,直接显示
18 os.environ  获取系统环境变量
19 os.path.abspath(path)  返回path规范化的绝对路径
20 os.path.split(path)  将path分割成目录和文件名二元组返回
21 os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
22 os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
23 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)  如果path是绝对路径,返回True
25 os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
26 os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
28 os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
29 os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

四、sys模块

1 sys.argv           命令行参数List,第一个元素是程序本身路径
2 sys.exit(n)        退出程序,正常退出时exit(0)
3 sys.version        获取Python解释程序的版本信息
4 sys.maxint         最大的Int值
5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
6 sys.platform       返回操作系统平台名称
7 sys.stdout.write('please:')
8 val = sys.stdin.readline()[:-1]

五、shutil 模块

高级的 文件、文件夹、压缩包 处理模块

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.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件

例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

shutil.move(src, dst)
递归的去移动文件

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如:www                        =>保存至当前路径
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象
1 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
2  
3 import shutil
4 ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
5  
6  
7 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
8 import shutil
9 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

 1 import zipfile
 2 
 3 # 压缩,压缩任意一个文件
 4 z = zipfile.ZipFile('laxi.zip', 'w')
 5 z.write('a.log')
 6 z.write('data.data')
 7 z.close()
 8 
 9 # 解压
10 z = zipfile.ZipFile('laxi.zip', 'r')
11 z.extractall()
12 z.close()
 1 import tarfile
 2 
 3 # 压缩
 4 tar = tarfile.open('your.tar','w')
 5 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
 6 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
 7 tar.close()
 8 
 9 # 解压
10 tar = tarfile.open('your.tar','r')
11 tar.extractall()  # 可设置解压地址
12 tar.close()

六、json & pickle 模块

参见Python基础-4

七、shelve 模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

 1 import shelve
 2  
 3 d = shelve.open('shelve_test') #打开一个文件
 4  
 5 class Test(object):
 6     def __init__(self,n):
 7         self.n = n
 8  
 9  
10 t = Test(123) 
11 t2 = Test(123334)
12  
13 name = ["Freeman","rain","test"]
14 d["test"] = name #持久化列表
15 d["t1"] = t      #持久化类
16 d["t2"] = t2
17  
18 d.close()

 八、xml处理模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

xml的格式如下,就是通过<>节点来区别数据结构的:

 1 <?xml version="1.0"?>
 2 <data>
 3     <country name="Liechtenstein">
 4         <rank updated="yes">2</rank>
 5         <year>2008</year>
 6         <gdppc>141100</gdppc>
 7         <neighbor name="Austria" direction="E"/>
 8         <neighbor name="Switzerland" direction="W"/>
 9     </country>
10     <country name="Singapore">
11         <rank updated="yes">5</rank>
12         <year>2011</year>
13         <gdppc>59900</gdppc>
14         <neighbor name="Malaysia" direction="N"/>
15     </country>
16     <country name="Panama">
17         <rank updated="yes">69</rank>
18         <year>2011</year>
19         <gdppc>13600</gdppc>
20         <neighbor name="Costa Rica" direction="W"/>
21         <neighbor name="Colombia" direction="E"/>
22     </country>
23 </data>

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xm

 1 import xml.etree.ElementTree as ET
 2  
 3 tree = ET.parse("xmltest.xml")
 4 root = tree.getroot()
 5 print(root.tag)
 6  
 7 #遍历xml文档
 8 for child in root:
 9     print(child.tag, child.attrib)
10     for i in child:
11         print(i.tag,i.text)
12  
13 #只遍历year 节点
14 for node in root.iter('year'):
15     print(node.tag,node.text)

修改和删除xml文档内容

 1 import xml.etree.ElementTree as ET
 2  
 3 tree = ET.parse("xmltest.xml")
 4 root = tree.getroot()
 5  
 6 #修改
 7 for node in root.iter('year'):
 8     new_year = int(node.text) + 1
 9     node.text = str(new_year)
10     node.set("updated","yes")
11  
12 tree.write("xmltest.xml")
13  
14  
15 #删除node
16 for country in root.findall('country'):
17    rank = int(country.find('rank').text)
18    if rank > 50:
19      root.remove(country)
20  
21 tree.write('output.xml')

自己创建xml文档

 1 import xml.etree.ElementTree as ET
 2  
 3  
 4 new_xml = ET.Element("namelist")
 5 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
 6 age = ET.SubElement(name,"age",attrib={"checked":"no"})
 7 sex = ET.SubElement(name,"sex")
 8 age.text = '33'
 9 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
10 age = ET.SubElement(name2,"age")
11 age.text = '19'
12  
13 et = ET.ElementTree(new_xml) #生成文档对象
14 et.write("test.xml", encoding="utf-8",xml_declaration=True)
15  
16 ET.dump(new_xml) #打印生成的格式

九、PyYAML模块

Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 

十、hashlib模块

用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

Python基础-5第2张Python基础-5第3张
 1 import hashlib
 2  
 3 m = hashlib.md5()
 4 m.update(b"Hello")
 5 m.update(b"It's me")
 6 print(m.digest())
 7 m.update(b"It's been a long time since last time we ...")
 8  
 9 print(m.digest()) #2进制格式hash
10 print(len(m.hexdigest())) #16进制格式hash
11 '''
12 def digest(self, *args, **kwargs): # real signature unknown
13     """ Return the digest value as a string of binary data. """
14     pass
15  
16 def hexdigest(self, *args, **kwargs): # real signature unknown
17     """ Return the digest value as a string of hexadecimal digits. """
18     pass
19  
20 '''
21 import hashlib
22  
23 # ######## md5 ########
24  
25 hash = hashlib.md5()
26 hash.update('admin')
27 print(hash.hexdigest())
28  
29 # ######## sha1 ########
30  
31 hash = hashlib.sha1()
32 hash.update('admin')
33 print(hash.hexdigest())
34  
35 # ######## sha256 ########
36  
37 hash = hashlib.sha256()
38 hash.update('admin')
39 print(hash.hexdigest())
40  
41  
42 # ######## sha384 ########
43  
44 hash = hashlib.sha384()
45 hash.update('admin')
46 print(hash.hexdigest())
47  
48 # ######## sha512 ########
49  
50 hash = hashlib.sha512()
51 hash.update('admin')
52 print(hash.hexdigest())
View Code

十一、re模块

 1 '.'     默认匹配除
之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
 2 '^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","
abc
eee",flags=re.MULTILINE)
 3 '$'     匹配字符结尾,或e.search("foo$","bfoo
sdfsf",flags=re.MULTILINE).group()也可以
 4 '*'     匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac")  结果为['abb', 'ab', 'a']
 5 '+'     匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
 6 '?'     匹配前一个字符1次或0次
 7 '{m}'   匹配前一个字符m次
 8 '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
 9 '|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
10 '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
11  
12  
13 'A'    只从字符开头匹配,re.search("Aabc","alexabc") 是匹配不到的
14 ''    匹配字符结尾,同$
15 'd'    匹配数字0-9
16 'D'    匹配非数字
17 'w'    匹配[A-Za-z0-9]
18 'W'    匹配非[A-Za-z0-9]
19 's'     匹配空白字符、	、
、
 , re.search("s+","ab	c1
3").group() 结果 '	'
20  
21 '(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}

最常用的匹配语法

1 re.match 从头开始匹配
2 re.search 匹配包含
3 re.findall 把所有匹配到的字符放到以列表中的元素返回
4 re.splitall 以匹配到的字符当做列表分隔符
5 re.sub      匹配字符并替换

几个匹配模式

1 re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
2 M(MULTILINE): 多行模式,改变'^''$'的行为(参见上图)
3 S(DOTALL): 点任意匹配模式,改变'.'的行为

免责声明:文章转载自《Python基础-5》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Linux环境下Gitblit服务搭建及秘钥配置jSignature手写签名下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

wordpress学习二:源码目录结构和启动流程

wordpress安装后的文件目录如下: 其中的主要目录和文件用途介绍如下: wp-admin:用于进行博客后台设置的功能目录 wp-content: wordpress的 主题,插件和本地化的存储目录 wp-include: wordpress一些类和公共函数文件的存放目录。 根目录下的index.php是大部分wordpress功能的入口模块。 大概...

【Python】 压缩文件处理 zipfile &amp;amp; tarfile

【zipfile】 虽然叫zipfile,但是除了zip之外,rar,war,jar这些压缩(或者打包)文件格式也都可以处理。   zipfile模块常用的一些操作和方法:     is_zipfile(filename)  测试filename的文件,看它是否是个有效的zipfile     ZipFile(filename[,mode[,compres...

pywinauto客户端自动化---pywinauto初始

目前流行的自动化就是web,app,接口算是目前最主流的测试内容了,那么如果让做安装windows上的客户端自动化呢?是不是一脸懵?今天安静给大家介绍python的第三方库,可以帮助我们做客户端的自动化 pywinauto pywinauto是一组用于自动化Microsoft Windows GUI的python模块。 最简单的是,它允许您将鼠标和键盘操作...

linux重新安装python

第一步:下载python2.7  wget https://www.Python.org/ftp/python/2.7.12/Python-2.7.12.tar.xz 第二步: 解压刚刚下载的压缩包 #tar -xvf Python-2.7.12.tar.xz 第三步:新建安装目录 mkdir /usr/local/Python27 第四步: 编译./co...

离线安装 Python三方包

方式一: 首先我们得从PyPI上先下载要装的第三方包 PyPI官方网址 :https://pypi.org/ PyPI(Python Package Index)是python官方的第三方bai库的仓库,所有人都可以下载第三方库或上传自己开发zhi的库到PyPI。PyPI推荐使用pip包管理器来下载第三方库。 下载下来我们需要安装的三方包 有一些包在安...

python基础之读取xml

python怎么操作xml文件详细介绍链接:https://www.jb51.net/article/50812.htm 从结构上来说,xml很像常见的HTML超文本标记语言。不过超文本语言被设计用来显示数据,其焦点是数据的外观。xml被设计用来传输和存储数据,其焦点是数据的内容。 特征: 1. 标签对组成:<TEST></TEST>...