1. 程式人生 > >四、常用模組

四、常用模組

  • 一 time與datetime模組
  • 二 random模組
  • 三 os模組
  • 四 sys模組
  • 五 shutil模組
  • 六 json&pickle模組
  • 七 shelve模組
  • 八 xml模組
  • 九 configparser模組
  • 十 hashlib模組
  • 十一 suprocess模組
  • 十二 logging模組
  • 十三 re模組

一 time與datetime模組

在Python中,通常有這幾種方式來表示時間:

  • 時間戳(timestamp):通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們執行“type(time.time())”,返回的是float型別。
  • 格式化的時間字串(Format String)
  • 結構化的時間(struct_time):struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時)
1 import time
2 #--------------------------我們先以當前時間為準,讓大家快速認識三種形式的時間
3 print(time.time()) # 時間戳:1487130156.419527
4 print(time.strftime("%Y-%m-%d %X")) #格式化的時間字串:'2017-02-15 11:40:53'
5 
6 print
(time.localtime()) #本地時區的struct_time 7 print(time.gmtime()) #UTC時區的struct_time
View Code
%a    Locale’s abbreviated weekday name.     
%A    Locale’s full weekday name.     
%b    Locale’s abbreviated month name.     
%B    Locale’s full month name.     
%c    Locale’s appropriate date and
time representation. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. (1) %S Second as a decimal number [00,61]. (2) %U Week 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) %w Weekday as a decimal number [0(Sunday),6]. %W Week 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) %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %z Time 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]. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character. 格式化字串的時間格式
格式化字串的時間格式

  其中計算機認識的時間只能是'時間戳'格式,而程式設計師可處理的或者說人類能看懂的時間有: '格式化的時間字串','結構化的時間' ,於是有了下圖的轉換關係

 

#--------------------------按圖1轉換時間
# localtime([secs])
# 將一個時間戳轉換為當前時區的struct_time。secs引數未提供,則以當前時間為準。
time.localtime()
time.localtime(1473525444.037215)

# gmtime([secs]) 和localtime()方法類似,gmtime()方法是將一個時間戳轉換為UTC時區(0時區)的struct_time。

# mktime(t) : 將一個struct_time轉化為時間戳。
print(time.mktime(time.localtime()))#1473525749.0


# strftime(format[, t]) : 把一個代表時間的元組或者struct_time(如由time.localtime()和
# time.gmtime()返回)轉化為格式化的時間字串。如果t未指定,將傳入time.localtime()。如果元組中任何一個
# 元素越界,ValueError的錯誤將會被丟擲。
print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56

# time.strptime(string[, format])
# 把一個格式化時間字串轉化為struct_time。實際上它和strftime()是逆操作。
print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
#  tm_wday=3, tm_yday=125, tm_isdst=-1)
#在這個函式中,format預設為:"%a %b %d %H:%M:%S %Y"。
View Code

 

 

1 #--------------------------按圖2轉換時間
2 # asctime([t]) : 把一個表示時間的元組或者struct_time表示為這種形式:'Sun Jun 20 23:21:05 1993'。
3 # 如果沒有引數,將會將time.localtime()作為引數傳入。
4 print(time.asctime())#Sun Sep 11 00:43:43 2016
5 
6 # ctime([secs]) : 把一個時間戳(按秒計算的浮點數)轉化為time.asctime()的形式。如果引數未給或者為
7 # None的時候,將會預設time.time()為引數。它的作用相當於time.asctime(time.localtime(secs))。
8 print(time.ctime())  # Sun Sep 11 00:46:38 2016
9 print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016
View Code
1 #--------------------------其他用法
2 # sleep(secs)
3 # 執行緒推遲指定的時間執行,單位為秒。
View Code
#時間加減
import datetime

# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) )  # 時間戳直接轉成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #當前時間+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #當前時間-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當前時間+3小時
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當前時間+30分


#
# c_time  = datetime.datetime.now()
datetime模組

二 random模組

import random
 
print(random.random())#(0,1)----float    大於0且小於1之間的小數
 
print(random.randint(1,3))  #[1,3]    大於等於1且小於等於3之間的整數
 
print(random.randrange(1,3)) #[1,3)    大於等於1且小於3之間的整數
 
print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
 
print(random.sample([1,'23',[4,5]],2))#列表元素任意2個組合
 
print(random.uniform(1,3))#大於1小於3的小數,如1.927109612082716 
 
 
item=[1,3,5,7,9]
random.shuffle(item) #打亂item的順序,相當於"洗牌"
print(item)
View Code
 1 import random
 2 def make_code(n):
 3     res=''
 4     for i in range(n):
 5         s1=chr(random.randint(65,90))
 6         s2=str(random.randint(0,9))
 7         res+=random.choice([s1,s2])
 8     return res
 9 
10 print(make_code(9))
生成隨機驗證碼

三 os模組

  os模組是與作業系統互動的一個介面

  

os.getcwd() 獲取當前工作目錄,即當前python指令碼工作的目錄路徑
os.chdir("dirname")  改變當前指令碼工作目錄;相當於shell下cd
os.curdir  返回當前目錄: ('.')
os.pardir  獲取當前目錄的父目錄字串名:('..')
os.makedirs('dirname1/dirname2')    可生成多層遞迴目錄
os.removedirs('dirname1')    若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推
os.mkdir('dirname')    生成單級目錄;相當於shell中mkdir dirname
os.rmdir('dirname')    刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
os.listdir('dirname')    列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印
os.remove()  刪除一個檔案
os.rename("oldname","newname")  重新命名檔案/目錄
os.stat('path/filename')  獲取檔案/目錄資訊
os.sep    輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/"
os.linesep    輸出當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n"
os.pathsep    輸出用於分割檔案路徑的字串 win下為;,Linux下為:
os.name    輸出字串指示當前使用平臺。win->'nt'; Linux->'posix'
os.system("bash command")  執行shell命令,直接顯示
os.environ  獲取系統環境變數
os.path.abspath(path)  返回path規範化的絕對路徑
os.path.split(path)  將path分割成目錄和檔名二元組返回
os.path.dirname(path)  返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path)  返回path最後的檔名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是絕對路徑,返回True
os.path.isfile(path)  如果path是一個存在的檔案,返回True。否則返回False
os.path.isdir(path)  如果path是一個存在的目錄,則返回True。否則返回False
os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑之前的引數將被忽略
os.path.getatime(path)  返回path所指向的檔案或者目錄的最後存取時間
os.path.getmtime(path)  返回path所指向的檔案或者目錄的最後修改時間
os.path.getsize(path) 返回path的大小
View Code
在Linux和Mac平臺上,該函式會原樣返回path,在windows平臺上會將路徑中所有字元轉換為小寫,並將所有斜槓轉換為飯斜槓。
>>> os.path.normcase('c:/windows\\system32\\')   
'c:\\windows\\system32\\'   
   

規範化路徑,如..和/
>>> os.path.normpath('c://windows\\System32\\../Temp/')   
'c:\\windows\\Temp'   

>>> a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
>>> print(os.path.normpath(a))
/Users/jieli/test1
View Code
os路徑處理
#方式一:推薦使用
import os
#具體應用
import os,sys
possible_topdir = os.path.normpath(os.path.join(
    os.path.abspath(__file__),
    os.pardir, #上一級
    os.pardir,
    os.pardir
))
sys.path.insert(0,possible_topdir)


#方式二:不推薦使用
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
View Code

四 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       返回作業系統平臺名稱

#=========知識儲備==========
#進度條的效果
[#             ]
[##            ]
[###           ]
[####          ]

#指定寬度
print('[%-15s]' %'#')
print('[%-15s]' %'##')
print('[%-15s]' %'###')
print('[%-15s]' %'####')

#列印%
print('%s%%' %(100)) #第二個%號代表取消第一個%的特殊意義

#可傳參來控制寬度
print('[%%-%ds]' %50) #[%-50s]
print(('[%%-%ds]' %50) %'#')
print(('[%%-%ds]' %50) %'##')
print(('[%%-%ds]' %50) %'###')


#=========實現列印進度條函式==========
import sys
import time

def progress(percent,width=50):
    if percent >= 1:
        percent=1
    show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')
    print('\r%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')


#=========應用==========
data_size=1025
recv_size=0
while recv_size < data_size:
    time.sleep(0.1) #模擬資料的傳輸延遲
    recv_size+=1024 #每次收1024

    percent=recv_size/data_size #接收的比例
    progress(percent,width=70) #進度條的寬度70

列印進度條
列印進度條

五 shutil模組  

  高階的 檔案、資料夾、壓縮包 處理模組

  shutil.copyfileobj(fsrc, fdst[, length])
  將檔案內容拷貝到另一個檔案中

  
1 import shutil
2  
3 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
View Code

shutil.copyfile(src, dst)
拷貝檔案

1 shutil.copyfile('f1.log', 'f2.log') #目標檔案無需存在

 

shutil.copymode(src, dst)
僅拷貝許可權。內容、組、使用者均不變

1 shutil.copymode('f1.log', 'f2.log') #目標檔案必須存在

 

shutil.copystat(src, dst)
僅拷貝狀態的資訊,包括:mode bits, atime, mtime, flags

1 shutil.copystat('f1.log', 'f2.log') #目標檔案必須存在

 

shutil.copy(src, dst)
拷貝檔案和許可權

1 import shutil
2  
3 shutil.copy('f1.log', 'f2.log')

 

shutil.copy2(src, dst)
拷貝檔案和狀態資訊

1 import shutil
2  
3 shutil.copy2('f1.log', 'f2.log')

 

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
遞迴的去拷貝資料夾

1 import shutil
2  
3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目標目錄不能存在,注意對folder2目錄父級目錄要有可寫許可權,ignore的意思是排除 
  拷貝軟連線

 

shutil.rmtree(path[, ignore_errors[, onerror]])
遞迴的去刪除檔案

1 import shutil
2  
3 shutil.rmtree('folder1')

 

shutil.move(src, dst)
遞迴的去移動檔案,它類似mv命令,其實就是重新命名。

1 import shutil
2  
3 shutil.move('folder1', 'folder3')

 

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

建立壓縮包並返回檔案路徑,例如:zip、tar

建立壓縮包並返回檔案路徑,例如:zip、tar

    • base_name: 壓縮包的檔名,也可以是壓縮包的路徑。只是檔名時,則儲存至當前目錄,否則儲存至指定路徑,
      如 data_bak                       =>儲存至當前路徑
      如:/tmp/data_bak =>儲存至/tmp/
    • format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要壓縮的資料夾路徑(預設當前目錄)
    • owner: 使用者,預設當前使用者
    • group: 組,預設當前組
    • logger: 用於記錄日誌,通常是logging.Logger物件
#將 /data 下的檔案打包放置當前程式目錄
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
  
  
#將 /data下的檔案打包放置 /tmp/目錄
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

  shutil 對壓縮包的處理是呼叫 ZipFile 和 TarFile 兩個模組來進行的,詳細:

  

import zipfile

# 壓縮
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解壓
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()

zipfile壓縮解壓縮
View Code
import tarfile

# 壓縮
>>> t=tarfile.open('/tmp/egon.tar','w')
>>> t.add('/test1/a.py',arcname='a.bak')
>>> t.add('/test1/b.py',arcname='b.bak')
>>> t.close()


# 解壓
>>> t=tarfile.open('/tmp/egon.tar','r')
>>> t.extractall('/egon')
>>> t.close()

tarfile壓縮解壓縮
tarfile壓縮解壓縮

六 json&pickle模組

  之前我們學習過用eval內建方法可以將一個字串轉成python物件,不過,eval方法是有侷限性的,對於普通的資料型別,json.loads和eval都能用,但遇到特殊型別的時候,eval就不管用了,所以eval的重點還是通常用來執行一個字串表示式,並返回表示式的值。

1 import json
2 x="[null,true,false,1]"
3 print(eval(x)) #報錯,無法解析null型別,而json就可以
4 print(json.loads(x)) 

什麼是序列化?

  我們把物件(變數)從記憶體中變成可儲存或傳輸的過程稱之為序列化,在Python中叫pickling,在其他語言中也被稱之為serialization,marshalling,flattening等等,都是一個意思。

為什麼要序列化?

1:持久儲存狀態

  需知一個軟體/程式的執行就在處理一系列狀態的變化,在程式語言中,'狀態'會以各種各樣有結構的資料型別(也可簡單的理解為變數)的形式被儲存在記憶體中。

記憶體是無法永久儲存資料的,當程式運行了一段時間,我們斷電或者重啟程式,記憶體中關於這個程式的之前一段時間的資料(有結構)都被清空了。

在斷電或重啟程式之前將程式當前記憶體中所有的資料都儲存下來(儲存到檔案中),以便於下次程式執行能夠從檔案中載入之前的資料,然後繼續執行,這就是序列化。

具體的來說,你玩使命召喚闖到了第13關,你儲存遊戲狀態,關機走人,下次再玩,還能從上次的位置開始繼續闖關。或如,虛擬機器狀態的掛起等。

2:跨平臺資料互動

序列化之後,不僅可以把序列化後的內容寫入磁碟,還可以通過網路傳輸到別的機器上,如果收發的雙方約定好實用一種序列化的格式,那麼便打破了平臺/語言差異化帶來的限制,實現了跨平臺資料互動。

反過來,把變數內容從序列化的物件重新讀到記憶體裡稱之為反序列化,即unpickling。

如何序列化之json和pickle:

json

  如果我們要在不同的程式語言之間傳遞物件,就必須把物件序列化為標準格式,比如XML,但更好的方法是序列化為JSON,因為JSON表示出來就是一個字串,可以被所有語言讀取,也可以方便地儲存到磁碟或者通過網路傳輸。JSON不僅是標準格式,並且比XML更快,而且可以直接在Web頁面中讀取,非常方便。

JSON表示的物件就是標準的JavaScript語言的物件,JSON和Python內建的資料型別對應如下:



 1 import json
 2  
 3 dic={'name':'alvin','age':23,'sex':'male'}
 4 print(type(dic))#<class 'dict'>
 5  
 6 j=json.dumps(dic)
 7 print(type(j))#<class 'str'>
 8  
 9  
10 f=open('序列化物件','w')
11 f.write(j)  #-------------------等價於json.dump(dic,f)
12 f.close()
13 #-----------------------------反序列化<br>
14 import json
15 f=open('序列化物件')
16 data=json.loads(f.read())#  等價於data=json.load(f)
View Code
import json
#dct="{'1':111}"#json 不認單引號
#dct=str({"1":111})#報錯,因為生成的資料還是單引號:{'one': 1}

dct='{"1":"111"}'
print(json.loads(dct))

#conclusion:
#        無論資料是怎樣建立的,只要滿足json格式,就可以json.loads出來,不一定非要dumps的資料才能loads
注意點

pickle

1 import pickle
 2  
 3 dic={'name':'alvin','age':23,'sex':'male'}
 4  
 5 print(type(dic))#<class 'dict'>
 6  
 7 j=pickle.dumps(dic)
 8 print(type(j))#<class 'bytes'>
 9  
10  
11 f=open('序列化物件_pickle','wb')#注意是w是寫入str,wb是寫入bytes,j是'bytes'
12 f.write(j)  #-------------------等價於pickle.dump(dic,f)
13  
14 f.close()
15 #-------------------------反序列化
16 import pickle
17 f=open('序列化物件_pickle','rb')
18  
19 data=pickle.loads(f.read())#  等價於data=pickle.load(f)
20  
21  
22 print(data['age'])  
View Code

  Pickle的問題和所有其他程式語言特有的序列化問題一樣,就是它只能用於Python,並且可能不同版本的Python彼此都不相容,因此,只能用Pickle儲存那些不重要的資料,不能成功地反序列化也沒關係。

七 shelve模組

  shelve模組比pickle模組簡單,只有一個open函式,返回類似字典的物件,可讀可寫;key必須為字串,而值可以是python所支援的資料型別。
import shelve

f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}

print(f['stu1_info']['hobby'])
f.close()
View Code

八 xml模組

  xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的介面還主要是xml。

  xml的格式如下,就是通過<>節點來區別資料結構的:

  

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

xml資料
xml資料

  xml協議在各個語言裡的都 是支援的,在python中可以用以下模組操作xml:

  
# print(root.iter('year')) #全文搜尋
# print(root.find('country')) #在root的子節點找,只找一個
# print(root.findall('country')) #在root的子節點找,找所有
import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
 
#遍歷xml文件
for child in root:
    print('========>',child.tag,child.attrib,child.attrib['name'])
    for i in child:
        print(i.tag,i.attrib,i.text)
 
#只遍歷year 節點
for node in root.iter('year'):
    print(node.tag,node.text)
#---------------------------------------

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
 
#修改
for node in root.iter('year'):
    new_year=int(node.text)+1
    node.text=str(new_year)
    node.set('updated','yes')
    node.set('version','1.0')
tree.write('test.xml')
 
 
#刪除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')
View Code
#在country內新增(append)節點year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root=tree.getroot()
for country in root.findall('country'):
    for year in country.findall('year'):
        if int(year.text) > 2000:
            year2=ET.Element('year2')
            year2.text='新年'
            year2.attrib={'update':'yes'}
            country.append(year2) #往country節點下新增子節點

tree.write('a.xml.swap')

  自己建立xml文件:

  

import xml.etree.ElementTree as ET
 
 
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
 
et = ET.ElementTree(new_xml) #生成文件物件
et.write("test.xml", encoding="utf-8",xml_declaration=True)
 
ET.dump(new_xml) #列印生成的格式

九 configparser模組

# 註釋1
; 註釋2

[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31

[section2]
k1 = v1
View Code

  讀取

import configparser

config=configparser.ConfigParser()
config.read('a.cfg')

#檢視所有的標題
res=config.sections() #['section1', 'section2']
print(res)

#檢視標題section1下所有key=value的key
options=config.options('section1')
print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

#檢視標題section1下所有key=value的(key,value)格式
item_list=config.items('section1')
print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]

#檢視標題section1下user的值=>字串格式
val=config.get('section1','user')
print(val) #egon

#檢視標題section1下age的值=>整數格式
val1=config.getint('section1','age')
print(val1) #18

#檢視標題section1下is_admin的值=>布林值格式
val2=config.getboolean('section1','is_admin')
print(val2) #True

#檢視標題section1下salary的值=>浮點型格式
val3=config.getfloat('section1','salary')
print(val3) #31.0

  改寫

import configparser

config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8')


#刪除整個標題section2
config.remove_section('section2')

#刪除標題section1下的某個k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')

#判斷是否存在某個標題
print(config.has_section('section1'))

#判斷標題section1下是否有user
print(config.has_option('section1',''))


#新增一個標題
config.add_section('egon')

#在標題egon下新增name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #報錯,必須是字串


#最後將修改的內容寫入檔案,完成最終的修改
config.write(open('a.cfg','w'))
View Code
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)

基於上述方法新增一個ini文件
基於上述方法新增一個ini文件

十 hashlib模組

# 1、什麼叫hash:hash是一種演算法(3.x裡代替了md5模組和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法),該演算法接受傳入的內容,經過運算得到一串hash值
# 2、hash值的特點是:
#2.1 只要傳入的內容一樣,得到的hash值必然一樣=====>要用明文傳輸密碼檔案完整性校驗
#2.2 不能由hash值返解成內容=======》把密碼做成hash值,不應該在網路傳輸明文密碼
#2.3 只要使用的hash演算法不變,無論校驗的內容有多大,得到的hash值長度是固定的

  hash演算法就像一座工廠,工廠接收你送來的原材料(可以用m.update()為工廠運送原材料),經過加工返回的產品就是hash值

 

import hashlib
 
m=hashlib.md5()# m=hashlib.sha256()
 
m.update('hello'.encode('utf8'))
print(m.hexdigest())  #5d41402abc4b2a76b9719d911017c592
 
m.update('alvin'.encode('utf8'))
 
print(m.hexdigest())  #92a7e713c30abbb0319fa07da2a5c4af
 
m2=hashlib.md5()
m2.update('helloalvin'.encode('utf8'))
print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

'''
注意:把一段很長的資料update多次,與一次update這段長資料,得到的結果一樣
但是update多次為校驗大檔案提供了可能。
'''
View Code

  以上加密演算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密演算法中新增自定義key再來做加密。

  
import hashlib
 
# ######## 256 ########
 
hash = hashlib.sha256('898oaFs09f'.encode('utf8'))
hash.update('alvin'.encode('utf8'))
print (hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7
import hashlib
passwds=[
    'alex3714',
    'alex1313',
    'alex94139413',
    'alex123456',
    '123456alex',
    'a123lex',
    ]
def make_passwd_dic(passwds):
    dic={}
    for passwd in passwds:
        m=hashlib.md5()
        m.update(passwd.encode('utf-8'))
        dic[passwd]=m.hexdigest()
    return dic

def break_code(cryptograph,passwd_dic):
    for k,v in passwd_dic.items():
        if v == cryptograph:
            print('密碼是===>\033[46m%s\033[0m' %k)

cryptograph='aee949757a2e698417463d47acac93df'
break_code(cryptograph,make_passwd_dic(passwds))

模擬撞庫破解密碼
模擬撞庫破解密碼

python 還有一個 hmac 模組,它內部對我們建立 key 和 內容 進行進一步的處理然後再加密:

1 import hmac
2 h = hmac.new('alvin'.encode('utf8'))
3 h.update('hello'.encode('utf8'))
4 print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940