python常用模块用法_python常用模块(一)
#什么是模塊呢?就是用一大坨代碼來(lái)完成一個(gè)功能的代碼集合,是不是簡(jiǎn)單易懂
#類(lèi)似于函數(shù)式編程和面向過(guò)程編程,函數(shù)式編程則完成一個(gè)功能,其他代碼用來(lái)調(diào)用即可,提供了代碼的重用性和代碼間的耦合。而對(duì)于一個(gè)復(fù)雜的功能來(lái),可能需要多個(gè)函數(shù)才能完成(函數(shù)又可以在不同的.py文件中),n個(gè) .py 文件組成的代碼集合就稱(chēng)為模塊。
如:os 是系統(tǒng)相關(guān)的模塊;file是文件操作相關(guān)的模塊
模塊分為三種:
自定義模塊
內(nèi)置標(biāo)準(zhǔn)模塊(又稱(chēng)標(biāo)準(zhǔn)庫(kù))
開(kāi)源模塊
#既然別人可以寫(xiě)一個(gè)代碼集合組成模塊,我們自然也可以,這就是自定義模塊
自定義模塊 和開(kāi)源模塊的使用參考?http://www.cnblogs.com/wupeiqi/articles/4963027.html
1.json模塊
用法:
1 importjson2 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:將數(shù)據(jù)通過(guò)特殊的形式轉(zhuǎn)換為所有程序語(yǔ)言都認(rèn)識(shí)的字符串
16 ,并放入文件,第一個(gè)參數(shù)是字典對(duì)象,第二個(gè)是文件對(duì)象17 #dumps:將數(shù)據(jù)通過(guò)特殊的形式轉(zhuǎn)換為所有程序語(yǔ)言都認(rèn)識(shí)的字符串
18 #loads:將json編碼的字符串再轉(zhuǎn)換為python的數(shù)據(jù)結(jié)構(gòu)
19 #load:從數(shù)據(jù)文件中讀取數(shù)據(jù),并將json編碼的字符串轉(zhuǎn)換為python的數(shù)據(jù)結(jié)構(gòu)
20
21 #說(shuō)明:
22 json編碼支持的基本類(lèi)型有:None, bool, int, float, string, list, tuple, dict.23
24 對(duì)于字典,json會(huì)假設(shè)key是字符串(字典中的任何非字符串key都會(huì)在編碼時(shí)轉(zhuǎn)換為字符串),要符合JSON規(guī)范,應(yīng)該只對(duì)python列表和字典進(jìn)行編碼。此外,在WEB應(yīng)用中,把最頂層對(duì)象定義為字典是一種標(biāo)準(zhǔn)做法。25
26 json編碼的格式幾乎和python語(yǔ)法一致,略有不同的是:True會(huì)被映射為true,False會(huì)被映射為false,None會(huì)被映射為null,元組()會(huì)被映射為列表[],因?yàn)槠渌Z(yǔ)言沒(méi)有元組的概念,只有數(shù)組,也就是列表。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 importpickle2
3 defhello():4 for i in range(10):5 print('Hello',i)6 returnhello7 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所有的數(shù)據(jù)類(lèi)型,但僅允許在python中使用(等于是python獨(dú)有語(yǔ)法),與json不同,不管能否反序列化,都可以序列化
16 #如果你重新開(kāi)個(gè)程序
17 importpickle18 with open('pickle.txt','rb') as f:19 a =pickle.loads(f.read())20 print(a)21 #則會(huì)報(bào)錯(cuò)'AttributeError: Can't get attribute 'hello' on
22 #那如果調(diào)用‘L’則毫無(wú)問(wèn)題,因?yàn)榇娴牟皇莾?nèi)存地址,而是數(shù)據(jù)
23 #所以說(shuō)內(nèi)存地址用完則釋放,兩個(gè)程序無(wú)法互相訪問(wèn)內(nèi)存地址,數(shù)據(jù)可以直接反序列化
24
25 #當(dāng)然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 importtime2
3 print(time.clock()) #返回處理器時(shí)間,3.3開(kāi)始已廢棄 , 改成了time.process_time()測(cè)量處理器運(yùn)算時(shí)間,不包括sleep時(shí)間,不穩(wěn)定,mac上測(cè)不出來(lái)
4 print(time.altzone) #返回與utc時(shí)間的時(shí)間差,以秒計(jì)算\
5 print(time.asctime()) #返回時(shí)間格式"Mon Nov 6 17:21:39 2017"
6 print(time.localtime()) #返回本地時(shí)間 的struct time對(duì)象格式
7 print(time.gmtime(time.time()-800000)) #返回utc時(shí)間的struc時(shí)間對(duì)象格式
8 print(time.asctime(time.localtime())) #返回時(shí)間格式"Mon Nov 6 17:31:19 2017"
9 print(time.ctime()) 同上10
11 #日期字符串 轉(zhuǎn)成 時(shí)間戳
12
13 string_struct = time.strptime('2017/11/13',"%Y/%m/%d") #將 日期字符串 轉(zhuǎn)成 struct時(shí)間對(duì)象格式
14 print(string_struct)15 str_stamp = time.mktime(string_struct) #將struct時(shí)間對(duì)象轉(zhuǎn)成時(shí)間戳
16 print(str_stamp)17
18 #時(shí)間戳轉(zhuǎn)成日期字符串
19
20 print(time.gmtime(time.time()-86640))21 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))22
23 #時(shí)間加減
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 #時(shí)間戳直接轉(zhuǎn)成日期字符串
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 #加一小時(shí)
35 print(datetime.datetime.now() + datetime.timedelta(hours=-1))36 >>>2017-11-13 16:33:00.117320 #減一小時(shí)
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 #時(shí)間替換
View Code
4.random模塊
用法:
1 importrandom2
3 #生成隨機(jī)數(shù)
4 print(random.random())5 print(random.randint(1,10000)) #給隨機(jī)數(shù)指定范圍,最高為10000
6 print(random.randrange(1,10000000000)) #給隨機(jī)數(shù)指定范圍,最高9999999999
7
8 #生成隨機(jī)驗(yàn)證碼
9
10 importrandom11 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模塊
提供對(duì)操作系統(tǒng)進(jìn)行調(diào)用的接口
用法:
1 importos2
3 print(os.getcwd())4 >>>c:\test.py #查看當(dāng)前路徑(類(lèi)似shell的pwd)
5 os.chdir('test')6 print(os.getcwd())7 >>>c:\test\test2 #改變當(dāng)前路徑(類(lèi)似shell的cd)
8 os.curdir #返回當(dāng)前目錄 (類(lèi)似shell的cd .)
9 os.pardir #返回父級(jí)目錄(類(lèi)似shell的 cd ..)
10 os.makedirs('P1/P2/P3') #創(chuàng)建多級(jí)目錄
11 os.removedirs('A/B/C') #刪除多級(jí)目錄,比如(A/B/C) 如果C是空的則刪除,不是則不刪除,并返回錯(cuò)誤,依次往上一級(jí)推
12 os.mkdir('test') #創(chuàng)建目錄('mkdir')
13 os.rmdir('test') #刪除目錄,不為空則刪除失敗
14 os.listdir('test') #列出目錄下的所有文件和所有目錄
15 os.remove('test') #刪除一個(gè)文件
16 os.rename('oldtest','newtest') #修改文件或目錄名字
17 print(os.stat('oldtest') #獲取文件或目錄信息
18 print(os.sep ) #返回系統(tǒng)路徑分隔符
19 print(os.linesep) #返回行的終止符
20 print(os.pathsep ) #返回分割文件路徑的字符串
21 os.environ #獲取系統(tǒng)環(huán)境變量
22 os.system("ping 1.1.1.1") #直接執(zhí)行shell的命令
23 print(os.path.abspath('C:')) #返回規(guī)范化的絕對(duì)路徑
24 print(os.path.split('c:/test'))25 >>>('c:', 'test') #將目錄和文件以二元組的方式返回
26 print(os.path.dirname(path)) #返回父級(jí)目錄,即'os.path.split'的第一個(gè)元素
27 print(os.path.basename('path')) #返回結(jié)束的文件名,即'os.path.split'的第二個(gè)元素
28 os.path.exists(path) #如果path存在,返回True;如果path不存在,返回False
29 os.path.isabs(path) #如果path是絕對(duì)路徑,返回True
30 os.path.isfile(path) #如果path是一個(gè)存在的文件,返回True。否則返回False
31 os.path.isdir(path) #如果path是一個(gè)存在的目錄,則返回True。否則返回False
32 os.path.join(path1[, path2[, ...]]) #將多個(gè)路徑組合后返回,第一個(gè)絕對(duì)路徑之前的參數(shù)將被忽略
33 os.path.getatime(path) #返回path所指向的文件或者目錄的最后存取時(shí)間
34 os.path.getmtime(path) #返回path所指向的文件或者目錄的最后修改時(shí)間
View Code
6.sys模塊
用法:
1 sys.argv #配合腳本使用可以讀取從外面?zhèn)鬟M(jìn)來(lái)的參數(shù)
2 print(sys.version) #查看python版本
3 sys.exit() #退出程序
4 sys.path #返回模塊搜索路徑,還有python環(huán)境變量
5 #還有modules,stdin,stdout,大家自己去查吧
View Code
7.shutil模塊
用法:
1 importshutil2
3 f1 = open('1.txt')4 f2 = open('2.txt','w',encoding='utf-8')5 shutil.copyfileobj(f1,f2) #復(fù)制文件
6 shutil.copyfile('1.txt','2.txt') #可直接復(fù)制
7 shutil.copytree('1','2') #復(fù)制目錄,整個(gè)目錄
8 shutil.rmtree('2') #刪除目錄
9 shutil.move(src,stc) #移動(dòng)
10 shutil.make_archive('C:/1','zip','D:/test') #壓縮,打包
11
12 #還有兩種壓縮方式:'Zipfile','Tarfile'
13
14 Zipfile:15 壓縮:16 z = zipfile.ZipFile('test.zip','w') #一個(gè)一個(gè)選擇壓縮
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 #跟上面差不多,舉個(gè)例子
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是一個(gè)簡(jiǎn)單的的key,vlaue將內(nèi)存數(shù)據(jù)通過(guò)文件持久化的模塊,可以持久化任何pickle可支持的python數(shù)據(jù)格式
用法:
1 importshelve2
3 d = shelve.open('shelve_test') #打開(kāi)一個(gè)文件
4
5 classTest(object):6 def __init__(self, n):7 self.n =n8
9 t = Test(123)10 t2 = Test(123334)11
12 name = ["alex", "rain", "test"]13 d["test"] = name #持久化列表
14 d["t1"] = t #持久化類(lèi)
15 d["t2"] =t216
17 d.close()18 d = shelve.open('shelve_test') #讀取
19 print(d.get('test'))20 >>>['alex', 'rain', 'test']
View Code
9.xml模塊
xml是實(shí)現(xiàn)不同語(yǔ)言或程序之間進(jìn)行數(shù)據(jù)交換的協(xié)議,跟json差不多,但json使用起來(lái)更簡(jiǎn)單,不過(guò),古時(shí)候,在json還沒(méi)誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統(tǒng)公司如金融行業(yè)的很多系統(tǒng)的接口還主要是xml。
xml的格式如下,就是通過(guò)<>節(jié)點(diǎn)來(lái)區(qū)別數(shù)據(jù)結(jié)構(gòu)的:
1 <?xml version="1.0"?>
2
3
4 2
5 2008
6 141100
7
8
9
10
11 5
12 2011
13 59900
14
15
16
17 69
18 2011
19 13600
20
21
22
23
XML文件
1 importxml.etree.ElementTree as ET2 tree = ET.parse("XML")3 root =tree.getroot()4
5 #讀取全部
6 print(root.tag)7 for child inroot:8 print(child.tag, child.attrib)9 for i inchild:10 print(i.tag,i.text)11
12 #只讀取其中一項(xiàng)比如(year)
13 for node in root.iter('year'):14 print(node.tag,node.text)15
16
17 #修改xml文件的內(nèi)容
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文件的內(nèi)容
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文檔格式,只不過(guò)需要安裝一個(gè)模塊,參考文檔:http://pyyaml.org/wiki/PyYAMLDocumentation
總結(jié)
以上是生活随笔為你收集整理的python常用模块用法_python常用模块(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: qfile指定从多少行开始_大牛进化路上
- 下一篇: python tkinter库 密码实时