Day04——Python模組,day04python
一、模組簡介
模組是實現了某個功能的代碼集合,比如幾個.py檔案可以組成代碼集合即模組。其中常見的模組有os模組(系統相關),file模組(檔案操作相關)
模組主要分三類:
- 自訂模組 :所謂自訂模組,即自己編寫Python檔案組成的模組。
- 第三方模組 :採用其他人編寫的模組,即第三方提供的模組
- 內建模組:python內建的模組
二、模組匯入
匯入模組的方法有好幾種方式,其中可以直接匯入,也可匯入模組的方法
import modulefrom module.xx.xx import xxfrom module.xx.xx import xx as rename from module.xx.xx import *
匯入模組其實就是告訴Python解譯器去解釋那個py檔案
- 匯入一個py檔案,解譯器解釋該py檔案
- 匯入一個包,解譯器解釋該包下的 __init__.py 檔案 【py2.7】
注意:
匯入模組時候,預設讀取的路徑為sys.path,可以通過下面的方法查看當前系統預設路徑:
import sysprint sys.path
輸出結果如下:
['', '/usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg', '/usr/lib/python2.7/site-packages/setuptools-19.4-py2.7.egg', '/usr/lib/python2.7/site-packages/Django-1.8.8-py2.7.egg', '/usr/lib/python2.7/site-packages/django_pagination-1.0.7-py2.7.egg', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages']
匯入模組時候,如果其不再預設路徑裡,則可以通過以下方法將其加入預設路徑
import sysimport osproject_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(project_path)
三、常用內建模組
內建模組是Python內建的功能,在使用時,需要先匯入再使用
1、sys模組
用於提供python解譯器相關操作
import sys
sys.argv 命令列參數List,第一個元素是程式本身路徑sys.exit(n) 退出程式,正常退出時exit(0)sys.version 擷取Python解釋程式的版本資訊sys.maxint 最大的Int值sys.path 返回模組的搜尋路徑,初始化時使用PYTHONPATH環境變數的值sys.platform 返回作業系統平台名稱sys.stdin 輸入相關sys.stdout 輸出相關sys.stderror 錯誤相關
2、os模組
提供系統層級的操作
os.getcwd() 擷取當前工作目錄,即當前python指令碼工作的目錄路徑os.chdir("dirname") 改變當前指令碼工作目錄;相當於shell下cdos.curdir 返回目前的目錄: ('.')os.pardir 擷取目前的目錄的父目錄字元串名:('..')os.makedirs('dir1/dir2') 可產生多層遞迴目錄os.removedirs('dirname1') 若目錄為空白,則刪除,並遞迴到上一級目錄,如若也為空白,則刪除,依此類推os.mkdir('dirname') 產生單級目錄;相當於shell中mkdir dirnameos.rmdir('dirname') 刪除單級空目錄,若目錄不為空白則無法刪除,報錯;相當於shell中rmdir dirnameos.listdir('dirname') 列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印os.remove() 刪除一個檔案os.rename("oldname","new") 重新命名檔案/目錄os.stat('path/filename') 擷取檔案/目錄資訊os.sep 作業系統特定的路徑分隔字元,win下為"\\",Linux下為"/"os.linesep 當前平台使用的行終止符,win下為"\t\n",Linux下為"\n"os.pathsep 用於分割檔案路徑的字串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不存在,返回Falseos.path.isabs(path) 如果path是絕對路徑,返回Trueos.path.isfile(path) 如果path是一個存在的檔案,返回True。否則返回Falseos.path.isdir(path) 如果path是一個存在的目錄,則返回True。否則返回Falseos.path.join(path1[, path2[, ...]]) 將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略os.path.getatime(path) 返回path所指向的檔案或者目錄的最後存取時間os.path.getmtime(path) 返回path所指向的檔案或者目錄的最後修改時間
3、hashlib模組
用於加密相關的操作,代替了md5模組和sha模組,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5演算法
import hashlib # ######## md5 ########hash = hashlib.md5()# help(hash.update)hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())print(hash.digest()) ######## sha1 ######## hash = hashlib.sha1()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512()hash.update(bytes('admin', encoding='utf-8'))print(hash.hexdigest())
hashlib直接加密可能會被裝庫破解密碼,所以這裡我們可以通過在密碼編譯演算法中自訂key做加密,具體樣本如下:
import hashlib # ######## md5 ######## hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))hash.update(bytes('admin',encoding="utf-8"))print(hash.hexdigest())
Python內建模組hmac可以對我們建立key和內容進行進一步的處理,然後加密
import hmac h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))h.update(bytes('admin',encoding="utf-8"))print(h.hexdigest())
4、random模組
用於產生隨機數的模組
import random
random.random() ##隨機取(0-1)之間的數值0.9151227988883402random.randint(1,3) ##隨機取[m-n]之間的整數3random.randrange(1,5) ##隨機取[m-n)之間的整數1random.choice('chinese') ##隨機取一個字元或列表數值's'random.choice([1,5,'abc'])1random.sample('hello',2) ##從字串中隨機取出N個字元['h', 'l']random.uniform(3,10) ##從區間(m,n)中取浮點數7.797497264321265l=[1,2,3,4,5] ##讓有序列表變無序random.shuffle(l) l[2, 4, 1, 5, 3]
編寫由數字和字母組成的4位驗證碼程式:(##大寫字母ascii:65-90,小寫字母:97-122)
#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangle##大寫字母ascii:65-90,小寫字母:97-122import randomcheck_code=''for i in range(4): num=random.randint(0,3) if num==i: num1=random.randint(0,3) if num==num1: code = chr(random.randint(65, 90)) else: code = chr(random.randint(97,122)) else: code=random.randint(1,9) check_code+=str(code)print(check_code)
5、re模組
re提供Regex相關操作
字元:
. 匹配除分行符號以外的任一字元
\w匹配字母或數字或底線或漢字
\s匹配任意的空白符
\d匹配數字
\b匹配單詞的開始或結束
^匹配字串的開始
$匹配字串的結束
次數:
* 重複零次或更多次
+重複一次或更多次
?重複零次或一次
{n}重複n次
{n,}重複n次或更多次
{n,m}重複n到m次
match:
match,從起始位置開始匹配,匹配成功返回一個對象,未匹配成功返回None
match(pattern, string, flags=0)
# match,從起始位置開始匹配,匹配成功返回一個對象,未匹配成功返回None match(pattern, string, flags=0) # pattern: 正則模型 # string : 要匹配的字串 # falgs : 匹配模式 X VERBOSE Ignore whitespace and comments for nicer looking RE's. I IGNORECASE Perform case-insensitive matching. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. A ASCII For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. U UNICODE For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns.
match文法
# 無分組 r = re.match("h\w+", origin) print(r.group()) # 擷取匹配到的所有結果 print(r.groups()) # 擷取模型中匹配到的分組結果 print(r.groupdict()) # 擷取模型中匹配到的分組結果 # 有分組 # 為何要有分組?提取匹配成功的指定內容(先匹配成功全部正則,再匹配成功的局部內容提取出來) r = re.match("h(\w+).*(?P<name>\d)$", origin) print(r.group()) # 擷取匹配到的所有結果 print(r.groups()) # 擷取模型中匹配到的分組結果 print(r.groupdict()) # 擷取模型中匹配到的分組中所有執行了key的組Demomatch樣本
search:
search,瀏覽整個字串去匹配第一個,未匹配成功返回None
search(pattern, string, flags=0)
# 無分組 r = re.search("a\w+", origin) print(r.group()) # 擷取匹配到的所有結果 print(r.groups()) # 擷取模型中匹配到的分組結果 print(r.groupdict()) # 擷取模型中匹配到的分組結果 # 有分組 r = re.search("a(\w+).*(?P<name>\d)$", origin) print(r.group()) # 擷取匹配到的所有結果 print(r.groups()) # 擷取模型中匹配到的分組結果 print(r.groupdict()) # 擷取模型中匹配到的分組中所有執行了key的組demosearch樣本
findall:
findall,擷取非重複的匹配列表;如果有一個組則以列表形式返回,且每一個匹配均是字串;如果模型中有多個組,則以列表形式返回,且每一個匹配均是元祖;
空的匹配也會包含在結果中
findall(pattern, string, flags=0)
# 無分組 r = re.findall("a\w+",origin) print(r) # 有分組 origin = "hello alex bcd abcd lge acd 19" r = re.findall("a((\w*)c)(d)", origin) print(r)Demofindall樣本
sub:
替換匹配成功的指定位置字串
sub(pattern, repl, string, count=0, flags=0)
pattern: 正則模型
repl : 要替換的字串或可執行對象
string : 要匹配的字串
count : 指定匹配個數
flags : 匹配模式
# 與分組無關origin = "hello alex bcd alex lge alex acd 19"r = re.sub("a\w+", "999", origin, 2)print(r)sub樣本
split:
split,根據正則匹配分割字串
split(pattern, string, maxsplit=0, flags=0)
pattern: 正則模型
string : 要匹配的字串
maxsplit:指定分割個數
flags : 匹配模式
# 無分組 origin = "hello alex bcd alex lge alex acd 19" r = re.split("alex", origin, 1) print(r) # 有分組 origin = "hello alex bcd alex lge alex acd 19" r1 = re.split("(alex)", origin, 1) print(r1) r2 = re.split("(al(ex))", origin, 1) print(r2)Demosplit樣本
常用正則匹配:
IP:^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$手機號:^1[3|4|5|8][0-9]\d{8}$郵箱:[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
6、序列化模組
Python中用於序列化的兩個模組
- json 用於【字串】和 【python基礎資料型別 (Elementary Data Type)】 間進行轉換
- pickle 用於【python特有的類型】 和 【python基礎資料型別 (Elementary Data Type)】間進行轉換
Json模組提供了四個功能:dumps、dump、loads、load
pickle模組提供了四個功能:dumps、dump、loads、load
#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangleimport jsonimport pickledata={'k1':123,'k2':'lucy'}p_str=pickle.dumps(data) ##將資料通過特殊形式轉化為只有Python語言認識的字串print(p_str)with open('F:\\python_project\\Day03\\test.txt','wb+') as fp: p_str=pickle.dump(data,fp) ##將資料通過特殊形式轉化為只有Python語言認識的字串,並寫入檔案j_str=json.dumps(data) ##將資料通過特殊形式轉為所有程式都認識的字串print(j_str)with open('F:\\python_project\\Day03\\test1.txt','w+') as fp: j_str=json.dump(data,fp) ##將資料通過特殊形式轉化為所有程式認識的字串,並寫入檔案
四、模組
發送