模塊
定義:用來從邏輯上組織python代碼(變量,函數(shù)死讹,累,邏輯:實現(xiàn)一個功能),本質(zhì)就是.py結(jié)尾的python文件(文件名:test.py對用的模塊名:test)
導(dǎo)入方法
import module_name
import module1_name,module2_name
from module_file import *
from module_file import module1_name,module2_name
from module_file import module_name as mn
import本質(zhì)(路徑搜索和搜索路徑)
導(dǎo)入模塊的本質(zhì)就是把python文件解釋一遍
導(dǎo)入包的本質(zhì)就是解釋包下面的init.py文件
包的本質(zhì):用來從邏輯上組織模塊间螟,本質(zhì)就是一個目錄(必須帶有一個init.py文件)
如果要導(dǎo)入包下面的模塊文件,就要修改init.py文件损肛,在里面導(dǎo)入模塊文件
模塊的分類
- 標(biāo)準(zhǔn)庫
- 開源模塊(第三方模塊)
- 自定義模塊
之前簡單做過介紹厢破,現(xiàn)在詳細(xì)介紹一下
http://www.reibang.com/p/239014d3aae9
標(biāo)準(zhǔn)庫
time、datetime模塊
python中治拿,通常有這幾種方式表示時間:
- 時間戳
- 格式化的時間字符串
- 元組(struct_time)共九個元素
時間戳:
表示從1970年1月1日00:00開始按秒計算偏移量摩泪,運行‘type(time.time())’,返回的是float類型,返回時間戳方式的函數(shù)主要有time()
元組(struct_time):
struct_time元組共有9個元素劫谅,返回struct_time的函數(shù)主要有g(shù)mtime()见坑、localtime()嚷掠、strptime()
time
import time
print(time.time())#得到當(dāng)前時間的時間戳
#輸出:1565966794.21425
print(time.timezone)#utc時間與本地時間的差值(時間戳)
#輸出:-28800
print(time.altzone)#utc時間與夏令時間的差值(時間戳)
#輸出:-32400
print(time.localtime())#返回本地時間的struct_time對象格式
#輸出:time.struct_time(tm_year=2019, tm_mon=8, tm_mday=16, tm_hour=22, tm_min=53, tm_sec=29, tm_wday=4, tm_yday=228, tm_isdst=0)
print(time.gmtime())#返回utc時間的struct_time對象格式
#輸出:time.struct_time(tm_year=2019, tm_mon=8, tm_mday=16, tm_hour=14, tm_min=58, tm_sec=3, tm_wday=4, tm_yday=228, tm_isdst=0)
print(time.asctime())#將struct_time對象格式轉(zhuǎn)換成本地時間格式:Fri Aug 16 23:00:14 2019
#輸出:Fri Aug 16 23:00:14 2019
print(time.ctime())#將時間戳轉(zhuǎn)換成本地時間格式:Fri Aug 16 23:00:14 2019
#輸出:Fri Aug 16 23:00:14 2019
string_struct=time.strptime('2019/8/16 23:04','%Y/%m/%d %H:%M')#將日期字符串轉(zhuǎn)成struct時間對象格式
print(string_struct)
#輸出:time.struct_time(tm_year=2019, tm_mon=8, tm_mday=16, tm_hour=23, tm_min=4, tm_sec=0, tm_wday=4, tm_yday=228, tm_isdst=-1)
print(time.strftime('%Y/%m/%d %H:%M',string_struct))#將struct時間對象轉(zhuǎn)成日期字符串
#輸出:2019/08/16 23:04
print(time.mktime(string_struct))#將struct時間對象轉(zhuǎn)成時間戳
#輸出:1565967840.0
struct_time和時間戳<->時間字符串格式的轉(zhuǎn)換:
格式化的時間字符串<->struct_time<->時間戳 的相互轉(zhuǎn)換
datetime
import datetime
print(datetime.datetime.now())#返回格式化日期格式
#輸出:2019-08-17 00:32:25.011494
print(datetime.datetime.now() + datetime.timedelta(3)) #當(dāng)前時間+3天
#輸出:2019-08-20 00:32:25.011494
print(datetime.datetime.now() + datetime.timedelta(-3)) #當(dāng)前時間-3天
#輸出:2019-08-14 00:32:25.011494
print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當(dāng)前時間+3小時
#輸出:2019-08-17 03:32:25.011494
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當(dāng)前時間+30分
#輸出:2019-08-17 01:02:25.011494
c_time = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2))#時間替換,將小時替換為2荞驴,分鐘變?yōu)?
#輸出:2019-08-17 02:03:25.011494
random模塊
import random
print(random.random())#取0-1的隨機(jī)浮點數(shù)
#輸出:0.07306541518636855
print(random.randint(1,3))#取[1,3]閉區(qū)間的整數(shù)
print(random.randrange(1,3))#取[1,3)半閉半開區(qū)間的整數(shù)
print(random.choice('abcde'))#隨機(jī)取字符串中的字符
print(random.choice([1,2,3,4,5,6]))#隨機(jī)取列表中的數(shù)據(jù)
print(random.sample('abcde',2))#隨機(jī)取兩位數(shù)據(jù)
#輸出:['b', 'e']
print(random.uniform(1,3))#炔唤浴(1,3)區(qū)間的浮點數(shù)
#輸出:2.1186016630230196
a=[1,2,3,4,5,6]
random.shuffle(a)#隨機(jī)打亂數(shù)據(jù)順序
print(a)
#輸出:[3, 1, 5, 6, 2, 4]
生成隨機(jī)驗證碼:
checkcode = ''
for i in range(6):
b_current = random.randrange(0,6)
if b_current != i:
s_current=random.randrange(0,6)
if s_current==b_current:
temp = chr(random.randint(97,122))
else:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print (checkcode)
os模塊
import os
print(os.getcwd())#獲取當(dāng)前工作目錄,即當(dāng)前python腳本工作的目錄路徑
os.chdir('C://')#改變當(dāng)前腳本工作目錄熊楼;相當(dāng)于shell下cd
print(os.curdir)#返回當(dāng)前目錄: ('.')
print(os.pardir)#獲取當(dāng)前目錄的父目錄字符串名:('..')
os.makedirs(r'd:\a\b\c')#可生成多層遞歸目錄
os.removedirs(r'd:\a\b\c')#若目錄為空霹娄,則刪除,并遞歸到上一級目錄孙蒙,如若也為空项棠,則刪除,依此類推
os.mkdir(r'd:a')#生成單級目錄挎峦;相當(dāng)于shell中mkdir dirname
os.rmdir(r'd:a')# 刪除單級空目錄香追,若目錄不為空則無法刪除,報錯坦胶;相當(dāng)于shell中rmdir dirname
print(os.listdir(r'd:'))#列出指定目錄下的所有文件和子目錄透典,包括隱藏文件,并以列表方式打印
#輸出:['$360Section', '$RECYCLE.BIN', '360Downloads', '360Rec', '360安全瀏覽器下載', 'BaiduNetdiskDownload', 'computer software', 'Config.Msi']
os.remove(r'd:\a')#刪除一個文件
os.rename(r'd:\a',r'd:\b')#重命名文件/目錄
print(os.stat(r'd:360安全瀏覽器下載'))#獲取文件/目錄信息
#輸出:os.stat_result(st_mode=16895, st_ino=5066549580791849, st_dev=485194, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1565493157, st_mtime=1565493157, st_ctime=1563296312)
print(os.environ)#當(dāng)前系統(tǒng)的環(huán)境變量
print(os.name)#輸出字符串指示當(dāng)前使用平臺顿苇。win->'nt'; Linux->'posix'
os.system('dir')#運行shell命令峭咒,直接顯示
print(os.path.abspath('./'))#返回path規(guī)范化的絕對路徑
print(os.path.split(r'd:a.txt'))#將path分割成目錄和文件名二元組返回
#輸出:('d:', 'a.txt')
print(os.path.dirname(os.path.abspath('./')))#返回path的目錄。其實就是os.path.split(path)的第一個元素
print(os.path.basename(os.path.abspath('./')))#返回path最后的文件名纪岁。如何path以/或\結(jié)尾凑队,那么就會返回空值。即os.path.split(path)的第二個元素
print(os.path.exists(os.path.abspath('./')))#判斷路徑是否存在幔翰,如果path存在漩氨,返回True;如果path不存在遗增,返回False
print(os.path.isabs(os.path.abspath('./')))#判斷路徑是否是絕對路徑
print(os.path.isfile(os.path.abspath('./')))#判斷路徑是否是文件
print(os.path.isdir(os.path.abspath('./')))#判斷路徑是否是目錄
print(os.path.join(r'dir\haha',r'module',r'file'))#將多個路徑組合后返回叫惊,第一個絕對路徑之前的參數(shù)將被忽略
#輸出:dir\haha\module\file
import time
struct_time=time.localtime(os.path.getatime(os.path.abspath('./')))
print(time.strftime('%Y-%m-%d %H:%M:%S',struct_time))#返回path所指向的文件或者目錄的最后存取時間,結(jié)果是時間戳,這里轉(zhuǎn)化為字符串時間格式
#輸出:2019-08-18 15:53:13
print(os.path.getmtime(os.path.abspath('./')))#返回path所指向的文件或者目錄的最后修改時間
#輸出:1566114793.5133495
print(os.sep)#輸出操作系統(tǒng)特定的路徑分隔符做修,win下為"\\",Linux下為"/"
print(os.linesep)#輸出當(dāng)前平臺使用的行終止符霍狰,win下為"\r\n",Linux下為"\n"
print(os.pathsep)#輸出用于分割文件路徑的字符串
具體實現(xiàn)如下圖:
sys模塊
#sys_module.py文件
import sys
print(sys.argv)#命令行參數(shù)List,第一個元素是程序本身路徑
#cmd命令運行 并帶上參數(shù)
E:\test\pycharm\file\python develop\day5>python sys_module.py 1 2 3 4 5
['sys_module.py', '1', '2', '3', '4', '5']
print(sys.version)#獲取Python解釋程序的版本信息
#輸出:3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]
print(sys.path)#返回模塊的搜索路徑饰及,初始化時使用PYTHONPATH環(huán)境變量的值
print(sys.platform)#返回操作系統(tǒng)平臺名稱
sys.exit(0)#退出程序蔗坯,正常退出時exit(0)
shutil模塊
高級的 文件、文件夾燎含、壓縮包 處理模塊
copyfileobj將文件內(nèi)容拷貝到另一個文件中步悠,可以部分內(nèi)容
f1=open('buweixia',encoding='utf-8')
f2=open('buweixia2','w',encoding='utf-8')
shutil.copyfileobj(f1,f2)
copyfile拷貝文件,自動打開文件
shutil.copyfile('buweixia2','buweixia3')
copystat拷貝狀態(tài)的信息瘫镇,包括:mode bits, atime, mtime, flags
import os
print(os.stat('buweixia2'))
shutil.copystat('buweixia2','buweixia3')
print(os.stat('buweixia3'))
#輸出:
# os.stat_result(st_mode=33206, st_ino=1688849860284406, st_dev=508939, st_nlink=1, st_uid=0, st_gid=0, st_size=1785, st_atime=1566120930, st_mtime=1566121662, st_ctime=1566120930)
# os.stat_result(st_mode=33206, st_ino=2251799813705719, st_dev=508939, st_nlink=1, st_uid=0, st_gid=0, st_size=1785, st_atime=1566120930, st_mtime=1566121662, st_ctime=1566121586)
copy拷貝文件和權(quán)限
shutil.copy('buweixia3','buweixia4')
copy2拷貝文件和狀態(tài)信息
shutil.copy2('buweixia3','buweixia5')
copytree遞歸的去拷貝文件
shutil.copytree('./copy_file','./haha')
rmtree遞歸的去刪除文件
shutil.rmtree('./copy_file')
move遞歸的去移動文件,且可以重命名目錄
shutil.move('./enen', './copy_file')
make_archive創(chuàng)建壓縮包并返回文件路徑鼎兽,例如:zip答姥、tar
- base_name: 壓縮包的文件名,也可以是壓縮包的路徑谚咬。只是文件名時鹦付,則保存至當(dāng)前目錄,否則保存至指定路徑择卦,
如:www =>保存至當(dāng)前路徑
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ - format:壓縮包種類敲长,“zip”, “tar”, “bztar”,“gztar”
- root_dir:要壓縮的文件夾路徑(默認(rèn)當(dāng)前目錄)
- owner:用戶秉继,默認(rèn)當(dāng)前用戶
- group: 組祈噪,默認(rèn)當(dāng)前組
- logger:用于記錄日志,通常是logging.Logger對象
shutil.make_archive('./tar_file','tar')
shelve模塊
將數(shù)據(jù)寫入文件:
import shelve
info={'age':24,'sex':'m'}
name=['haha','enen','yoyo']
test=(1,2,3,4)
f['test']=test
f['name']=name
f['info']=info
f.close()
讀取文件內(nèi)容:
import shelve
f=shelve.open('./copy_file/buwexia')
print(f.get('test'))
print(f.get('name'))
print(f.get('info'))
輸出:
(1, 2, 3, 4)
['haha', 'enen', 'yoyo']
{'age': 24, 'sex': 'm'}
xml模塊
xml是實現(xiàn)不同語言或程序之間進(jìn)行數(shù)據(jù)交換的協(xié)議尚辑,跟json差不多辑鲤,但json使用起來更簡單
# Author:haha
import xml.etree.ElementTree as ET
tree=ET.parse('xml_file')
root=tree.getroot()
print(root.tag)
#輸出:data
#遍歷整個xml文檔
for child in root:
print(child.tag,child.attrib)
for i in child:
print(i.tag,i.attrib,i.text)
#輸出:
'''
country {'name': 'Liechtenstein'}
rank {'updated': 'yes'} 2
year {} 2008
gdppc {} 141100
neighbor {'name': 'Austria', 'direction': 'E'} None
neighbor {'name': 'Switzerland', 'direction': 'W'} None
country {'name': 'Singapore'}
rank {'updated': 'yes'} 5
year {} 2011
gdppc {} 59900
neighbor {'name': 'Malaysia', 'direction': 'N'} None
country {'name': 'Panama'}
rank {'updated': 'yes'} 69
year {} 2011
gdppc {} 13600
neighbor {'name': 'Costa Rica', 'direction': 'W'} None
neighbor {'name': 'Colombia', 'direction': 'E'} None
'''
for child in root.iter('year'):#指定一個key值,查看text值
print(child.tag,child.text)
#輸出:
# year 2008
# year 2011
# year 2011
#修改和刪除xml文檔內(nèi)容
for child in root.iter('year'):
new_year=int(child.text)+2
child.text=str(new_year)
child.set('update','yes')
tree.write('xml_file')
for child in root.iter('year'):
print(child.tag,child.text)
#輸出:
# year 2010
# year 2013
# year 2013
for country in root.findall('country'):
rank=int(country.find('rank').text)
if rank>5:
root.remove(country)
tree.write('xml_file')
自己創(chuàng)建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")
name.text='haha'
age.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'
name2.text='enen'
et = ET.ElementTree(new_xml) # 生成文檔對象
et.write("test.xml", encoding="utf-8", xml_declaration=True)
ET.dump(new_xml) # 打印生成的格式
configparser
生成config配置文件
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'] = {}
config['topsecret.server.com']['Host Port'] = '50022' # mutates the parser
config['topsecret.server.com']['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini','w') as configfile:
config.write(configfile)
讀取配置文件
import configparser
config=configparser.ConfigParser()
config.read('example.ini')
print(config.sections())#打印除default外的其他節(jié)點
print(config['bitbucket.org']['user'])#打印指定節(jié)點下的數(shù)據(jù)
print(config.defaults())#打印default下面的配置數(shù)據(jù)
print('bitbucket.org' in config)#判斷指定數(shù)據(jù)是否在config中
print(config.options('bitbucket.org'))#打印指定節(jié)點的子列表+default下的key值數(shù)據(jù)
#輸出:['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.items('bitbucket.org'))#打印指定節(jié)點+default下的數(shù)據(jù)
#輸出:[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
print(config.get('bitbucket.org','user'))#打印指定節(jié)點下指定key值的value數(shù)據(jù)
#輸出:hg
print(config.getint('topsecret.server.com','host port'))#打印指定節(jié)點下指定key值的value int數(shù)據(jù)
#輸出:50022
修改
config.set('bitbucket.org','user','haha')#修改指定節(jié)點的指定key值的value值杠茬,沒有就創(chuàng)建
print(config.has_option('bitbucket.org','user'))#判斷指定節(jié)點是否包含指定key值
print(config.add_section('bitbucket.org'))#添加指定節(jié)點
print(config.has_section('bitbucket.org'))#判斷有無指定節(jié)點月褥,沒有就創(chuàng)建
config.remove_section('bitbucket.org')#刪除指定節(jié)點
config.remove_option('bitbucket.org','user')#刪除指定節(jié)點的指定key欄數(shù)據(jù)
config.write(open('example.ini','w'))#覆蓋原來的文件
hashlib模塊
用于加密相關(guān)的操作
md5加密:
import hashlib
md=hashlib.md5()
md.update(b'hello')
print(md.hexdigest())
md.update("It's me,哈哈".encode(encoding='utf-8'))
print(md.hexdigest())
#驗證
md2=hashlib.md5()
md2.update("helloIt's me,哈哈".encode(encoding='utf-8'))
print(md2.hexdigest())
#輸出:
'''
5d41402abc4b2a76b9719d911017c592
12c18ee8a7b5bfa3ccb0e98109f4b1ea
12c18ee8a7b5bfa3ccb0e98109f4b1ea
'''
其他加密模塊類似,只是將md5改為相對應(yīng)的加密方式瓢喉,例:sha256
import hashlib
sh=hashlib.sha256()
sh.update(b'hello')
print(sh.hexdigest())
sh.update("It's me,哈哈".encode(encoding='utf-8'))
print(sh.hexdigest())
#驗證
sh2=hashlib.sha256()
sh2.update("helloIt's me,哈哈".encode(encoding='utf-8'))
print(sh2.hexdigest())
#輸出:
'''
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
69bb59a9dd5d6b843423ddcbdf050aae0c0023d858dfe66a9b3edf3253791ec6
69bb59a9dd5d6b843423ddcbdf050aae0c0023d858dfe66a9b3edf3253791ec6
'''
hmac加密
更加高端的加密手段
import hmac
h=hmac.new("hello',b'It's me,哈哈".encode(encoding='utf-8'))
print(h.hexdigest())
#輸出:4c241f49f6acc0c8669d33a4ed805cd6
re模塊
常用正則表達(dá)式符號
'.' 默認(rèn)匹配除\n之外的任意一個字符宁赤,若指定flag DOTALL,則匹配任意字符,包括換行
'^' 匹配字符開頭栓票,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
'$' 匹配字符結(jié)尾决左,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*' 匹配*號前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 結(jié)果為['abb', 'ab', 'a']
'+' 匹配前一個字符1次或多次走贪,re.findall("ab+","ab+cd+abb+bba") 結(jié)果['ab', 'abb']
'?' 匹配前一個字符1次或0次
'{m}' 匹配前一個字符m次
'{n,m}' 匹配前一個字符n到m次佛猛,re.findall("ab{1,3}","abb abc abbcbbb") 結(jié)果'abb', 'ab', 'abb']
'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結(jié)果'ABC'
'(...)' 分組匹配厉斟,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結(jié)果 abcabca456c
'\A' 只從字符開頭匹配挚躯,re.search("\Aabc","alexabc") 是匹配不到的
'\Z' 匹配字符結(jié)尾强衡,同$
'\d' 匹配數(shù)字0-9
'\D' 匹配非數(shù)字
'\w' 匹配[A-Za-z0-9]
'\W' 匹配非[A-Za-z0-9]
's' 匹配空白字符擦秽、\t、\n漩勤、\r , re.search("\s+","ab\tc1\n3").group() 結(jié)果 '\t'
'(?P<name>...)' 分組匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 結(jié)果{'province': '3714', 'city': '81', 'birthday': '1993'}
re.match 從頭開始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符當(dāng)做列表分隔符
例:re.split('[0-9]','abc12f3GH'),結(jié)果為:['abc', '', 'f', 'GH']
re.sub 匹配字符并替換
例:re.sub('[0-9]+','|','abc12f3GH'),結(jié)果為:abc|f|GH
只替換一個數(shù)字:
re.sub('[0-9]+','|','abc12f3GH',count=1)感挥,結(jié)果為:abc|f3GH
注:
[] 單字符取一個,比如[abc]會匹配a或b或c
但是越败,如果[]里面加上^則會變成排除這個字符触幼,如[^abc]就表示不是a、不是b究飞、也不是c
另外置谦,在[]里面可以使用-表示一個范圍堂鲤,如[0-9]表示從0到9,類似的還有[a-zA-Z]媒峡,如果要包含-字符瘟栖,可以給它加上轉(zhuǎn)義[\-]。
關(guān)于[]常見的錯誤用法是:[ab|bc]用來表示ab或bc谅阿,實際上半哟,它得到的結(jié)果是[abc|],即a或b或c或|這4個字符(單字符)的任意一個签餐。這里可以改成(ab|bc)寓涨。
總結(jié):[]里面的特殊符有五個:[]-\^,其他字符都是普通字符氯檐,包括*.?等戒良。
說明:
* ^在[^ 的首位時候才有特殊意義
* [0-9 -在不是首尾的時候有特殊意義
* \[ \] 因為占用[] 本身字符,所以有特殊意義
* \本身是轉(zhuǎn)義符男摧,有特殊意義
反斜杠的困擾:
print(re.search(r'\\','abc\d'))
#輸出:<re.Match object; span=(3, 4), match='\\'>
flags匹配模式:
re.I(re.IGNORECASE): 忽略大小寫(括號內(nèi)是完整寫法蔬墩,下同)
例:re.search('[a-z]+','abcAMK',flags=re.I)
輸出:<re.Match object; span=(0, 6), match='abcAMK'>
M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖)
例:re.search('^[0-9]+','abcb\n123',flags=re.M)
輸出:<re.Match object; span=(5, 8), match='123'>
S(DOTALL): 點任意匹配模式耗拓,改變'.'的行為
例:re.search('.+','abcb\n123',flags=re.S)
輸出:<re.Match object; span=(0, 8), match='abcb\n123'>