Python常用模块二

一.time & datetime 

 1 #_*_coding:utf-8_*_
 2 
 3 
 4 import time
 5 
 6 
 7 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
 8 # print(time.altzone)  #返回与utc时间的时间差,以秒计算\
 9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
10 # print(time.localtime()) #返回本地时间 的struct time对象格式
11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
12 
13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
15 
16 
17 
18 # 日期字符串 转成  时间戳
19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
20 # print(string_2_struct)
21 # #
22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
23 # print(struct_2_stamp)
24 
25 
26 
27 #将时间戳转为字符串格式
28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
30 
31 
32 
33 
34 
35 #时间加减
36 import datetime
37 
38 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
39 #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
40 # print(datetime.datetime.now() )
41 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
42 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
43 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
44 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
45 
46 
47 #
48 # c_time  = datetime.datetime.now()
49 # print(c_time.replace(minute=3,hour=2)) #时间替换

二.random

1 import random
2 print(random.random())
3 print(random.randint(1,2))
4 print(random.randrange(1,10))

生成随机验证码

 1 import random
 2 checkcode = ''
 3 for i in range(4):
 4     current = random.randrange(0,4)
 5     if current != i:
 6         temp = chr(random.randint(65,90))
 7     else:
 8         temp = random.randint(0,9)
 9     checkcode += str(temp)
10 print(checkcode)

三.shutil模块

shutil模块提供了大量的文件的高级操作。特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作。对单个文件的操作也可参见os模块。

(1) 拷贝

1 >>> import shutil
2 >>> shutil.chown('test.txt',user='mysql',group='mysql') #改变文件的属主和属组
3 >>> shutil.copy('test.txt','test_copy.txt') #拷贝文件
4 >>> shutil.copy2('test.txt','test_copy2.txt') #拷贝文件并复制所有统计信息,如修改时间等。
5 >>> shutil.copyfile('test_ln.txt','test_copyfile.txt') #如果是链接文件,将复制新文件,不复制链接
 1 >>> dstf = open('test_copyfileobj.txt','r+')
 2 >>> srcf = open('test.txt','r')
 3 >>> shutil.copyfileobj(srcf,dstf,length=2)  #按长度拷贝文件对象
 4 
 5 >>> shutil.copymode('test.txt','test_copymode.txt')  #拷贝文件的权限到目标文件上
 6 
 7 >>> shutil.copystat('test.txt','test_copymode.txt')  #拷贝文件的访问和修改时间,其他不受影响
 8 #shutil.copytree(src, dst, symlinks=False, ignore=None) 递归的去拷贝文件夹
 9 #shutil.rmtree(path[, ignore_errors[, onerror]])  递归的去删除文件
10 #shutil.move(src, dst)  递归的去移动文件,它类似mv命令,其实就是重命名。

(2)压缩与解压缩

make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None)
创建压缩包并返回文件路径:
base_name:压缩包的文件名,也可以是压缩包的路径,只是文件名时,保存到当前目录,否则保存到指定路径
format:压缩包种类,‘zip’,'tar','bztar','gztar'
root_dir:要压缩的文件夹路径(默认当前目录)
owner:用户,默认当前用户
group:组,默认当前组
logger:用于记录日志,通常是logging.Logger对象
1 >>>import shutil
2 #将/root目录下的所有文件压缩到media目录下取名为www,压缩格式为tar
3 >>> ret = shutil.make_archive("/media/www",'tar',root_dir='/root')
4 
5 #将文件已tar格式压缩到当前目录下
6  ret = shutil.make_archive("ipython55",'tar',root_dir='/root/ipython-5.5.0')

shutil 对压缩包的处理是通过调用ZipFile 和 TarFile两个模块来进行的。

 1 >>> import zipfile
 2 #压缩
 3 >>> z = zipfile.ZipFile('xin.tar.gz','w')   #创建名为xin.tar.gz的压缩文件
 4 >>> z.write('test.txt')   #写入文件到压缩文件中
 5 >>> z.write('log.txt')
 6 >>> z.close()   #关闭文件
 7 #解压缩
 8 >>> z = zipfile.ZipFile('xin.tar.gz','r')   #打开压缩文件
 9 >>> z.extractall(path='/python/day7')  #解压到指定路径下
10 >>> z.close()
11 
12 
13 >>> import tarfile
14 #压缩
15 >>> tar = tarfile.open('/usr/targzfile.tar.gz','w')  #指定目录创建压缩文件
16 >>> tar.add('/python/day7/test1.py',arcname='test1.py')  #添加文件到压缩文件中
17 >>> tar.add('/python/day7/test1.py',arcname='test2.py')
18 >>> tar.close()
19 
20 #解压缩
21 >>> tar = tarfile.open('/usr/targzfile.tar.gz','r')
22 >>> tar.extractall(path='/pyhton/day8')
23 >>> tar.close()

四.xml模块

XML 指可扩展标记语言(eXtensible Markup Language),标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。

XML 被设计用来传输和存储数据。

XML是一套定义语义标记的规则,这些标记将文档分成许多部件并对这些部件加以标识。

它也是元标记语言,即定义了用于定义其他与特定领域有关的、语义的、结构化的标记语言的句法语言。

python对XML的解析:

常见的XML编程接口有DOM和SAX,这两种接口处理XML文件的方式不同,当然使用场合也不同。

python有三种方法解析XML,SAX,DOM,以及ElementTree:

使用xml.etree.ElementTree模块来解析XML文件,ElementTree模块中提供了两个类用来完成这个目的:

ElementTree表示整个XML文件(一个树形结构)

Element表示树种的一个元素(结点)

示例xml文件:

 1 <collection shelf="New Arrivals">
 2 <movie title="Enemy Behind">
 3    <type>War, Thriller</type>
 4    <format>DVD</format>
 5    <year>2003</year>
 6    <rating>PG</rating>
 7    <stars>10</stars>
 8    <description>Talk about a US-Japan war</description>
 9 </movie>
10 <movie title="Transformers">
11    <type>Anime, Science Fiction</type>
12    <format>DVD</format>
13    <year>1989</year>
14    <rating>R</rating>
15    <stars>8</stars>
16    <description>A schientific fiction</description>
17 </movie>
18    <movie title="Trigun">
19    <type>Anime, Action</type>
20    <format>DVD</format>
21    <episodes>4</episodes>
22    <rating>PG</rating>
23    <stars>10</stars>
24    <description>Vash the Stampede!</description>
25 </movie>
26 <movie title="Ishtar">
27    <type>Comedy</type>
28    <format>VHS</format>
29    <rating>PG</rating>
30    <stars>2</stars>
31    <description>Viewable boredom</description>
32 </movie>
33 </collection>

首先需要导入ElementTree模块:import xml.etree.ElementTree as ET

然后使用ET下的方法parse解析XML文档:ET.parse()

 1 >>> import tab
 2 >>> import xml.etree.ElementTree as ET   #导入模块
 3 >>> tree = ET.parse("xmltest.xml")  #解析xml文档
 4 >>> root = tree.getroot()   #获取根节点
 5 >>> print(root.tag)   #打印节点
 6 collection
 7 >>> print(root[1][1].tag,root[1][1].text)  #通过索引解析根的子节点和数值
 8 format DVD
 9 #取出整个xml文档的内容
10 >>> for child in root:   #循环根节点
11 ...   print(child.tag,child.attrib)  #打印节点和属性
12 ...   for i in child:   #再循环内层节点
13 ...     print("---",i.tag,i.text)  #打印节点和数值
14 ... 
15 #输出内容:
16 movie {'title': 'Enemy Behind'}
17 --- type War, Thriller
18 --- format DVD
19 --- year 2003
20 --- rating PG
21 --- stars 10
22 --- description Talk about a US-Japan war
23 movie {'title': 'Transformers'}
24 --- type Anime, Science Fiction
25 --- format DVD
26 --- year 1989
27 --- rating R
28 --- stars 8
29 --- description A schientific fiction
30 movie {'title': 'Trigun'}
31 --- type Anime, Action
32 --- format DVD
33 --- episodes 4
34 --- rating PG
35 --- stars 10
36 --- description Vash the Stampede!
37 movie {'title': 'Ishtar'}
38 --- type Comedy
39 --- format VHS
40 --- rating PG
41 --- stars 2
42 --- description Viewable boredom
43 
44 #只遍历type节点
45 >>> for i in root.iter('type'):  #iter检索节点名
46 ...   print(i.tag,i.text)
47 ... 
48 type War, Thriller
49 type Anime, Science Fiction
50 type Anime, Action
51 type Comedy

修改和添加属性,删除节点:

 1 >>> import tab
 2 >>> import xml.etree.ElementTree as ET
 3 >>> tree = ET.parse("xmltest.xml")
 4 >>> root = tree.getroot()
 5 
 6 >>> root[1][2].text = "2017"  #通过索引修改某个节点的值
 7 >>> tree.write('xmltest.xml')  #将修改写入文档中
 8 #循环修改索引的year节点数值
 9 >>> for i in root.iter('year'):
10 ...   new_year = int(i.text)+1
11 ...   i.text = str(new_year)
12 ...   i.set("updated","yes")  #为每个year节点添加属性
13 ... 
14 >>> tree.write("xmltest.xml")
15 
16 #删除某个节点
17 >>> for i in root.findall('stars'):   #查询所有stars节点并删除
18 ...   root.remove(i)

创建xml文档:

 1 #!/usr/bin/env python
 2 #coding:utf8
 3 
 4 import xml.etree.ElementTree as ET
 5 
 6 new_xml = ET.Element('namelist')  #创建根节点
 7 name = ET.SubElement(new_xml,"root",attrib={'enrolled':'yes'})   #根节点下创建子节点并设置属性
 8 age = ET.SubElement(name,"head",attrib={"cheched":"no"}) #root节点下创建节点,配置属性
 9 sex = ET.SubElement(name,"sex")  #root下创建节点
10 sex.text = '88'   #设置节点值
11 name2 = ET.SubElement(new_xml,"root",attrib={"enrolled":"no"})
12 age2 = ET.SubElement(name2,'age2')
13 age2.text = '99'
14 
15 et = ET.Element(new_xml)   #生成xml文件对象
16 #et.write("test_1.xml",encoding="utf-8",xml_declaration=True)
17 ET.dump(new_xml)   #打印生成格式
18 
19 #output:
20 <namelist>
21     <root enrolled="yes">
22         <head cheched="no" />
23         <sex>88</sex>
24     </root>
25     <root enrolled="no">
26         <age2>99</age2>
27     </root>
28 </namelist>

猜你喜欢

转载自www.cnblogs.com/itworks/p/9765691.html