python常用模块(一)


 #什么是模块呢?就是用一大坨代码来完成一个功能的代码集合,是不是简单易懂

#类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

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


#既然别人可以写一个代码集合组成模块,我们自然也可以,这就是自定义模块

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

1.json模块

用法:

 1 import json
 2 a = {
 3     '1':'a',
 4     '2':'b',
 5     '3':'c'
 6 }
 7 with open("1.txt",'r+') as f:
 8     json.dump(a,f)
 9     print(json.load(f))
10 >>>{'1': 'a', '2': 'b', '3': 'c'}
11     f.write(json.dumps(a))
12     print(json.loads(f.readline()))
13 >>>{'1': 'a', '2': 'b', '3': 'c'}
14 
15 #dump:将数据通过特殊的形式转换为所有程序语言都认识的字符串
16 ,并放入文件,第一个参数是字典对象,第二个是文件对象
17 #dumps:将数据通过特殊的形式转换为所有程序语言都认识的字符串
18 #loads:将json编码的字符串再转换为python的数据结构
19 #load:从数据文件中读取数据,并将json编码的字符串转换为python的数据结构
20 
21 #说明:
22 json编码支持的基本类型有:None, bool, int, float, string, list, tuple, dict.
23 
24   对于字典,json会假设key是字符串(字典中的任何非字符串key都会在编码时转换为字符串),要符合JSON规范,应该只对python列表和字典进行编码。此外,在WEB应用中,把最顶层对象定义为字典是一种标准做法。
25 
26   json编码的格式几乎和python语法一致,略有不同的是:True会被映射为true,False会被映射为false,None会被映射为null,元组()会被映射为列表[],因为其他语言没有元组的概念,只有数组,也就是列表。
27 a = {
28     '1':True,
29     '2':False,
30     '3':None,
31     '4':(1,2,3),
32     5:'qwe'
33 }
34 da = json.dumps(a)
35 print(da)
36 >>>{"1": true, "2": false, "3": null, "4": [1, 2, 3], "5": "qwe"}
View Code

2. pickle模块

用法:

 1 import pickle
 2 
 3 def hello():
 4     for i in range(10):
 5         print('Hello',i)
 6     return hello
 7 L = {
 8     'a':1,
 9     'b':2,
10     'c':'Daniel'
11 }
12 with open('pickle.txt','wb') as f:
13     f.write(pickle.dumps(hello))
14 with open('pickle.txt','wb') as f:
15     f.write(pickle.dumps(L))                     #pickle可以序列化python所有的数据类型,但仅允许在python中使用(等于是python独有语法),与json不同,不管能否反序列化,都可以序列化
16 #如果你重新开个程序
17 import  pickle
18 with open('pickle.txt','rb') as f:
19     a =pickle.loads(f.read())
20     print(a)
21 #则会报错'AttributeError: Can't get attribute 'hello' on <module '__main__'',因为你在前面那个程序定义了一个'hello',并且有它的内存地址,所以可以调用,但是到了这个新程序就没有了,要想调用,之你那个将''hello()''复制到新程序
22 #那如果调用‘L’则毫无问题,因为存的不是内存地址,而是数据
23 #所以说内存地址用完则释放,两个程序无法互相访问内存地址,数据可以直接反序列化
24 
25 #当然pickle也有'load'、'dump'
26 L = {
27     'a':1,
28     'b':2,
29     'c':'Daniel'
30 }
31 with open('pickle.txt','wb') as f:
32     pickle.dump(L,f)
33 with open('pickle.txt','rb') as f:
34     a = pickle.load(f)
35     print(a)
36 >>>{'a': 1, 'b': 2, 'c': 'Daniel'}
View Code

3.time & datetime模块

用法:

 1 import time
 2 
 3 print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
 4 print(time.altzone) #返回与utc时间的时间差,以秒计算
 5 print(time.asctime()) #返回时间格式"Mon Nov  6 17:21:39 2017"
 6 print(time.localtime()) #返回本地时间 的struct time对象格式
 7 print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
 8 print(time.asctime(time.localtime())) #返回时间格式"Mon Nov  6 17:31:19 2017"
 9 print(time.ctime()) 同上
10 
11 # 日期字符串 转成  时间戳
12 
13 string_struct = time.strptime('2017/11/13',"%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
14 print(string_struct)
15 str_stamp = time.mktime(string_struct)  #将struct时间对象转成时间戳
16 print(str_stamp)
17 
18 #时间戳转成日期字符串
19 
20 print(time.gmtime(time.time()-86640))
21 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
22 
23 #时间加减
24 
25 print(datetime.datetime.now())
26 >>>2017-11-13 17:33:00.117320
27 print(datetime.date.fromtimestamp(time.time()))
28 >>>2017-11-13         #时间戳直接转成日期字符串
29 print(datetime.datetime.now() + datetime.timedelta(3)) #加三天
30 >>>2017-11-16 17:33:00.117320 
31 print(datetime.datetime.now() + datetime.timedelta(-3)) #减三天
32 >>>2017-11-10 17:33:00.117320 
33 print(datetime.datetime.now() + datetime.timedelta(hours=1))
34 >>>2017-11-13 18:33:00.117320  #加一小时
35 print(datetime.datetime.now() + datetime.timedelta(hours=-1))
36 >>>2017-11-13 16:33:00.117320  #减一小时
37 print(datetime.datetime.now()+datetime.timedelta(minutes=10)) #加十分钟
38 >>>2017-11-13 17:43:00.117320
39 #so 那么就有秒----"second"不举例子了。=
40 print(now_time.replace(minute=0,hour=18,second=0,microsecond=0))
41 >>>2017-11-13 18:00:00  #时间替换
View Code

4.random模块

用法:

 1 import random
 2 
 3 #生成随机数
 4 print(random.random())  
 5 print(random.randint(1,10000)) #给随机数指定范围,最高为10000
 6 print(random.randrange(1,10000000000)) #给随机数指定范围,最高9999999999
 7 
 8 #生成随机验证码
 9 
10 import random
11 ver_code = ''
12 for i in range(5):
13     number = random.randrange(0,5)
14     if number != i:
15         letter = chr(random.randrange(65,99))
16     else:
17         letter = random.randint(0,9)
18     ver_code += str(letter)
19 print(ver_code)
View Code

5.os模块

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

用法:

 1 import os
 2 
 3 print(os.getcwd())
 4 >>>c:	est.py                                   #查看当前路径(类似shell的pwd)
 5 os.chdir('test')
 6 print(os.getcwd())
 7 >>>c:	est	est2                                 #改变当前路径(类似shell的cd)
 8 os.curdir                                          #返回当前目录 (类似shell的cd .)
 9 os.pardir                                          #返回父级目录(类似shell的 cd ..)
10 os.makedirs('P1/P2/P3')                  #创建多级目录
11 os.removedirs('A/B/C')                    #删除多级目录,比如(A/B/C) 如果C是空的则删除,不是则不删除,并返回错误,依次往上一级推
12 os.mkdir('test')                               #创建目录('mkdir')
13 os.rmdir('test')                                #删除目录,不为空则删除失败
14 os.listdir('test')                                #列出目录下的所有文件和所有目录
15 os.remove('test')                             #删除一个文件
16 os.rename('oldtest','newtest')         #修改文件或目录名字
17 print(os.stat('oldtest'#获取文件或目录信息
18 print(os.sep )                                   #返回系统路径分隔符
19 print(os.linesep)                               #返回行的终止符
20 print(os.pathsep )                            #返回分割文件路径的字符串
21 os.environ                                         #获取系统环境变量  
22 os.system("ping 1.1.1.1")                #直接执行shell的命令
23 print(os.path.abspath('C:'))            #返回规范化的绝对路径
24 print(os.path.split('c:/test'))
25 >>>('c:', 'test')                                     #将目录和文件以二元组的方式返回
26 print(os.path.dirname(path))         #返回父级目录,即'os.path.split'的第一个元素
27 print(os.path.basename('path'))      #返回结束的文件名,即'os.path.split'的第二个元素
28 os.path.exists(path)                       #如果path存在,返回True;如果path不存在,返回False
29 os.path.isabs(path)                       #如果path是绝对路径,返回True
30 os.path.isfile(path)                        #如果path是一个存在的文件,返回True。否则返回False
31 os.path.isdir(path)                         #如果path是一个存在的目录,则返回True。否则返回False
32 os.path.join(path1[, path2[, ...]])  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
33 os.path.getatime(path)                #返回path所指向的文件或者目录的最后存取时间
34 os.path.getmtime(path)               #返回path所指向的文件或者目录的最后修改时间
View Code

其他用法请点击我

6.sys模块

用法:

1 sys.argv                  #配合脚本使用可以读取从外面传进来的参数
2 print(sys.version)    #查看python版本
3 sys.exit()                 #退出程序
4 sys.path                  #返回模块搜索路径,还有python环境变量
5 #还有modules,stdin,stdout,大家自己去查吧
View Code

7.shutil模块

用法:

 1 import shutil
 2 
 3 f1 = open('1.txt')
 4 f2 = open('2.txt','w',encoding='utf-8')
 5 shutil.copyfileobj(f1,f2)                    #复制文件
 6 shutil.copyfile('1.txt','2.txt')             #可直接复制
 7 shutil.copytree('1','2')                      #复制目录,整个目录
 8 shutil.rmtree('2')                            #删除目录
 9 shutil.move(src,stc)                       #移动
10 shutil.make_archive('C:/1','zip','D:/test') #压缩,打包
11 
12 #还有两种压缩方式:'Zipfile','Tarfile'
13 
14 Zipfile:
15 压缩:
16 z = zipfile.ZipFile('test.zip','w')        #一个一个选择压缩
17 z.write('test1.py')
18 z.write('test2.py')
19 z.close()
20 解压:
21 z = zipfile.ZipFile('test.zip','r')
22 z.extractall()
23 z.close()
24 
25 Tarfile:
26 #跟上面差不多,举个例子
27 tar = tarfile.open('1.tar','w)
28 tar.add('test1.py')
29 tar.close()
30 #解压跟上面完全一样
31 tar.extractall()
32 tar.close()
View Code

其它请点击我

8.shelve模块

shelve是一个简单的的key,vlaue将内存数据通过文件持久化的模块,可以持久化任何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 t = Test(123)
10 t2 = Test(123334)
11 
12 name = ["alex", "rain", "test"]
13 d["test"] = name  # 持久化列表
14 d["t1"] = t  # 持久化类
15 d["t2"] = t2
16 
17 d.close()
18 d = shelve.open('shelve_test')    #读取
19 print(d.get('test'))
20 >>>['alex', 'rain', 'test']
View Code

 9.xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是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文件
 1 import xml.etree.ElementTree as ET
 2 tree = ET.parse("XML")
 3 root = tree.getroot()
 4 
 5 #读取全部
 6 print(root.tag)
 7 for child in root:
 8     print(child.tag, child.attrib)
 9     for i in child:
10         print(i.tag,i.text)
11 
12 #只读取其中一项比如(year)
13 for node in root.iter('year'):
14     print(node.tag,node.text)
15 
16 
17 #修改xml文件的内容
18 for node in root.iter('year'):
19     new_year = int(node.text) + 1
20     node.text = str(new_year)
21     node.set("updated", "yes")
22 
23 tree.write("XML")                                           #将year+1
24 
25 #删除xml文件的内容
26 for country in root.findall('country'):
27    rank = int(country.find('rank').text)
28    if rank > 50:
29      root.remove(country)
30  
31 tree.write('output.xml')                            #如果country下的rank大于50就删除country
32 
33 #有删有改有查自然也有增
34 new_xml = ET.Element('company')
35 post = ET.SubElement(new_xml,'post',attrib={"enrolled":"yes"})
36 name = ET.SubElement(post,'name',attrib={"ehecked":"no"})
37 age = ET.SubElement(name,'age')
38 post.text = 'General manager'
39 name.text = 'Daniel'
40 age.text = '18'
41 et = ET.ElementTree(new_xml)
42 et.write('XML',encoding='utf-8',xml_declaration=True)
43 ET.dump(new_xml)
处理XML文件

10.PyYaml

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


原文地址:https://www.cnblogs.com/wazy/p/7794040.html