Python自学——python的常用模块
Python學習——python的常用模塊
原文作者:佛山小程序員
原文鏈接:https://blog.csdn.net/weixin_44192923/article/details/86563253
模塊:用一堆代碼實現了某個功能的代碼集合,模塊是不帶 .py 擴展的另外一個 Python 文件的文件名。
最近開始整理python的資料,會陸續放到博客中存檔。找了幾個qq群,其中有一個群78486745。后面就沒怎么加群了,還是需要看官方文檔為主一、time & datetime模塊
1 import time2 import datetime3 4 print(time.asctime()) # 返回時間格式:Sun May 7 21:46:15 20175 print(time.time()) # 返回時間戳 ‘1494164954.6677325’6 print(time.gmtime()) # 返回本地時間 的struct time對象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)7 print(time.localtime()) # 返回本地時間 的struct time對象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)8 print(time.gmtime(time.time()-800000)) # 返回utc時間的struc時間對象格式9 print(time.asctime(time.localtime())) # 返回時間格式Sun May 7 22:15:09 2017 10 print(time.ctime()) # 返回時間格式Sun May 7 22:15:09 2017 11 print(time.strftime('%Y-%m-%d')) #默認當前時間 2017-05-07 12 print(time.strftime('%Y-%m-%d',time.localtime())) #默認當前時間 2017-05-07 13 14 string_struct = time.strptime("2016/05/22","%Y/%m/%d") # 將日期字符串 轉成 struct時間對象格式 15 print(string_struct) # 返回struct time對象格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1) 16 17 # 將日期字符串轉成時間戳 18 struct_stamp = time.mktime(string_struct) # 將struct time時間對象轉成時間戳 19 print(struct_stamp) # 返回時間戳 ‘1463846400.0’ 20 21 # 將時間戳轉為字符串格式 22 print(time.gmtime(time.time()-86640)) # 將utc時間戳轉換成struct_time格式 23 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) # 將utc struct_time格式轉成指定的字符串格式 24 25 26 # 時間加減 27 print(datetime.datetime.now()) # 返回當前時間 2017-05-07 22:36:45.179732 28 print(datetime.date.fromtimestamp(time.time())) # 時間戳直接轉換成日期格式 2017-05-07 29 print(datetime.datetime.now() + datetime.timedelta(3)) # 返回時間在當前日期上 +3 天 30 print(datetime.datetime.now() + datetime.timedelta(-3)) # 返回時間在當前日期上 -3 天 31 print(datetime.datetime.now() + datetime.timedelta(hours= 3)) # 返回時間在當前時間上 +3 小時 32 print(datetime.datetime.now() + datetime.timedelta(minutes= 30)) # 返回時間在當前時間上 +30 分鐘 33 34 c_time = datetime.datetime.now() 35 print(c_time) # 當前時間為 2017-05-07 22:52:44.016732 36 print(c_time.replace(minute=3,hour=2)) # 時間替換 替換時間為‘2017-05-07 02:03:18.181732’ 37 38 print(datetime.timedelta) # 表示時間間隔,即兩個時間點之間的長度 39 print (datetime.datetime.now() - datetime.timedelta(days=5)) # 返回時間在當前時間上 -5 天 40 41 # python 日歷模塊 42 import calendar 43 44 print(calendar.calendar(theyear= 2017)) # 返回2017年整年日歷 45 print(calendar.month(2017,5)) # 返回某年某月的日歷,返回類型為字符串類型 46 47 calendar.setfirstweekday(calendar.WEDNESDAY) # 設置日歷的第一天(第一天以星期三開始) 48 cal = calendar.month(2017, 4) 49 print (cal) 50 51 print(calendar.monthrange(2017,5)) # 返回某個月的第一天和這個月的所有天數 52 print(calendar.monthcalendar(2017,5)) # 返回某個月以每一周為元素的序列 53 54 cal = calendar.HTMLCalendar(calendar.MONDAY) 55 print(cal.formatmonth(2017, 5)) # 在html中打印某年某月的日歷 56 57 print(calendar.isleap(2017)) # 判斷是否為閏年 58 print(calendar.leapdays(2000,2017)) # 判斷兩個年份間閏年的個數二、random模塊
1 import random2 3 # 隨機數4 print(random.random()) # 返回一個隨機小數'0.4800545746046827'5 print(random.randint(1,5)) # 返回(1-5)隨機整型數據6 print(random.randrange(1,10)) # 返回(1-10)隨機數據7 8 # 生成隨機驗證碼9 code = '' 10 for i in range(4): 11 current = random.randrange(0,4) 12 if current != i: 13 temp = chr(random.randint(65,90)) 14 else: 15 temp = random.randint(0,9) 16 code += str(temp) 17 18 print(code)三、OS模塊
1 import os2 3 print(os.getcwd()) # 獲得當前工作目錄4 print(os.chdir("dirname")) # 改變當前腳本的工作路徑,相當于shell下的cd5 print(os.curdir) # 返回當前目錄‘.'6 print(os.pardir) # 獲取當前目錄的父目錄字符串名‘..'7 print(os.makedirs('dirname1/dirname2')) # 可生成多層遞歸目錄8 print(os.removedirs('dirname1/dirname2')) # 若目錄為空,則刪除,并遞歸到上一級目錄,如若也為空,則刪除,依此類推9 print(os.mkdir('test4')) # 生成單級目錄;相當于shell中mkdir dirname 10 print(os.rmdir('test4')) # 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當于shell中rmdir dirname 11 print(os.listdir('/pythonStudy/s12/test')) # 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印 12 print(os.remove('log.log')) # 刪除一個指定的文件 13 print(os.rename("oldname","newname")) # 重命名文件/目錄) 14 print(os.stat('/pythonStudy/s12/test')) # 獲取文件/目錄信息 15 print(os.pathsep) # 輸出用于分割文件路徑的字符串';' 16 print(os.name) # 輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix' 17 print(os.system(command='bash')) # 運行shell命令,直接顯示 18 print(os.environ) # 獲得系統的環境變量 19 print(os.path.abspath('/pythonStudy/s12/test')) # 返回path規范化的絕對路徑 20 print(os.path.split('/pythonStudy/s12/test')) # 將path分割成目錄和文件名二元組返回 21 print(os.path.dirname('/pythonStudy/s12/test')) # 返回path的目錄。其實就是os.path.split(path)的第一個元素 22 print(os.path.basename('/pythonStudy/s12/test')) # 返回path最后的文件名。如果path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素 23 print(os.path.exists('test')) # 判斷path是否存在 24 print(os.path.isabs('/pythonStudy/s12/test')) # 如果path是絕對路徑,返回True 25 print(os.path.isfile('test')) # 如果path是一個存在的文件,返回True。否則返回False 26 print(os.path.isdir('/pythonStudy/s12/test')) # 如果path是一個存在的目錄,則返回True。否則返回False 27 print(os.path.getatime('/pythonStudy/s12/test')) # 返回path所指向的文件或者目錄的最后存取時間 28 print(os.path.getmtime('/pythonStudy/s12/test')) # 返回path所指向的文件或者目錄的最后修改時間四、sys模塊
import sysprint(sys.argv) # 命令行參數List,第一個元素是程序本身路徑 print(sys.exit(n)) # 退出程序,正常退出時exit(0) print(sys.version) # 獲取python的版本信息 print(sys.path) # 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 print(sys.platform) # 返回操作平臺的名稱五、shutil模塊
import shutil shutil.copyfileobj(fsrc, fdst, length=16*1024) # 將文件內容拷貝到另一個文件中,可以是部分內容 shutil.copyfile(src, dst) # 拷貝文件 shutil.copymode(src, dst) # 僅拷貝權限。內容、組、用戶均不變 shutil.copystat(src, dst) # 拷貝狀態的信息,包括:mode bits, atime, mtime, flags shutil.copy(src, dst) # 拷貝文件和權限 shutil.copy2(src, dst) # 拷貝文件和狀態信息 shutil.move(src, dst) # 遞歸的去移動文件# base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑 # format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar” # root_dir: 要壓縮的文件夾路徑(默認當前目錄) # owner: 用戶,默認當前用戶 # group: 組,默認當前組 # logger: 用于記錄日志,通常是logging.Logger對象 shutil.make_archive(base_name, format,root_dir,owner,group,logger) # 創建壓縮包并返回文件路徑,例如:zip、tarshutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的:# zipfile 壓縮解壓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() z.close()# tarfile 壓縮解壓import tarfile# 壓縮 tar = tarfile.open('your.tar','w') tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip') tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip') tar.close()# 解壓 tar = tarfile.open('your.tar','r') tar.extractall() # 可設置解壓地址 tar.close()六、XML處理模塊
# xml的格式如下,就是通過<>節點來區別數據結構的: xmltest.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協議在各個語言里的都 是支持的,在python中可以用以下模塊操作xml import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag)#遍歷xml文檔 for child in root:print(child.tag, child.attrib)for i in child:print(i.tag,i.text)#只遍歷year 節點 for node in root.iter('year'):print(node.tag,node.text)# 修改和刪除xml文檔內容import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml") root = tree.getroot()#修改for node in root.iter('year'):new_year = int(node.text) + 1node.text = str(new_year)node.set("updated","yes") tree.write("xmltest.xml")#刪除nodefor country in root.findall('country'):rank = int(country.find('rank').text)if rank > 50:root.remove(country) tree.write('output.xml')# 自己創建xml文檔 import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist") name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"}) age = ET.SubElement(name, "age", attrib={"checked": "no"}) age = ET.SubElement(name, "age") age.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模塊
用于生成和修改常見配置文檔
# 好多軟件的常見文檔格式如下[DEFAULT]compressionlevel = 9serveraliveinterval = 45compression = yesforwardx11 = yes[bitbucket.org]user = hg[topsecret.server.com]host port = 50022forwardx11 = no# python 生成一個這樣的文檔import configparserconfig = 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'topsecret['ForwardX11'] = 'no'config['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') as configfile:config.write(configfile)# 寫完了還可以再讀出來import configparserconfig = configparser.ConfigParser()config.sections()file = config.read('example.ini')print(file) # ['example.ini']title = config.sections()print(title) # ['bitbucket.org', 'topsecret.server.com']print('bitbucket.org' in config) # Trueprint('bytebong.com' in config) # Falseprint(config['bitbucket.org']['User']) # hgprint(config['DEFAULT']['Compression']) # yestopsecret = config['topsecret.server.com']print(topsecret['ForwardX11']) # noprint(topsecret['Host Port']) # 50022for key in config['topsecret.server.com']:print(key)'''輸出結果:host portforwardx11compressionlevelserveraliveintervalcompression'''print(config['topsecret.server.com']['Compression']) # yes# configparser增刪改查語法 import configparserconfig = configparser.ConfigParser() config.read('i.cfg')secs = config.sections() # 返回配置文件中的主節點 print (secs)options = config.options('bitbucket.org') print(options) # 返回所有子節點信息item_list = config.items('bitbucket.org') print(item_list) # 列出所有子節點詳細信息val = config.get('topsecret.server.com','host port') print(val) # 返回單個子節點信息val2 = config.getint('topsecret.server.com','host port') print(val2)# 刪除'bitbucket.org' sec = config.remove_section('bitbucket.org') config.write(open('i.cfg','w'))sec2 = config.add_section('huhuan2') # 添加主節點 config.set('huhuan2','k','1111') # 添加子節點 config.set('huhuan','kk','2222') config.remove_option('huhuan','kk') # 刪除子節點 config.write(open('i.cfg','w'))八、hashlib模塊
用于加密相關的操作
import hashlib# ****** md5 ****** m =hashlib.md5() m.update(b'hello') print(m.hexdigest()) # 16進制格式 print(m.digest()) # 2進制格式# ****** shal ****** hash = hashlib.sha1() hash.update(b'hello') print(hash.hexdigest())# ****** sha224 ****** hash = hashlib.sha224() hash.update(b'hello') print(hash.hexdigest())# ****** sha256 ****** hash = hashlib.sha256() hash.update(b'hello') print(hash.hexdigest())# ****** sha384 ****** hash = hashlib.sha384() hash.update(b'hello') print(hash.hexdigest())# ****** sha512 ****** hash = hashlib.sha512() hash.update(b'hello') print(hash.hexdigest())運行結果: 5d41402abc4b2a76b9719d911017c592 b']A@*\xbcK*v\xb9q\x9d\x91\x10\x17\xc5\x92' aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043九、logging 模塊
python的logging模塊提供了標準的日志接口,你可以通過它存儲各種格式的日志,logging的日志可以分為 debug(), info(), warning(), error() and critical() 5個級別。
import logging# %(message)s 日志信息 # %(levelno)s 日志級別 # datefmt 設置時間格式 # filename 設置日志保存的路徑 # level=loggin.INFO意思是,把日志紀錄級別設置為INFO,也就是說,只有比日志是INFO或比INFO級別更高的日志才會被紀錄到文件里, # 在這個例子, 第一條日志是不會被紀錄的,如果希望紀錄debug的日志,那把日志級別改成DEBUG就行了。 logging.basicConfig(format='%(asctime)s %(message)s %(levelno)s', datefmt='%m/%d/%Y %I:%M:%S %p',filename='example.log',level=logging.INFO) logging.debug('This message should go to the log file') logging.info('So should this')日志格式
| %(name)s | Logger的名字 |
| %(levelno)s | 數字形式的日志級別 |
| %(levelname)s | 文本形式的日志級別 |
| %(pathname)s | 調用日志輸出函數的模塊的完整路徑名,可能沒有 |
| %(filename)s | 調用日志輸出函數的模塊的文件名 |
| %(module)s | 調用日志輸出函數的模塊名 |
| %(funcName)s | 調用日志輸出函數的函數名 |
| %(lineno)d | 調用日志輸出函數的語句所在的代碼行 |
| %(created)f | 當前時間,用UNIX標準的表示時間的浮 點數表示 |
| %(relativeCreated)d | 輸出日志信息時的,自Logger創建以 來的毫秒數 |
| %(asctime)s | 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒 |
| %(thread)d | 線程ID。可能沒有 |
| %(threadName)s | 線程名。可能沒有 |
| %(process)d | 進程ID。可能沒有 |
| %(message)s | 用戶輸出的消息 |
Python 使用logging模塊記錄日志涉及四個主要類:
logger提供了應用程序可以直接使用的接口;
handler將(logger創建的)日志記錄發送到合適的目的輸出;
filter提供了細度設備來決定輸出哪條日志記錄;
formatter決定日志記錄的最終輸出格式。
logger :
每個程序在輸出信息之前都要獲得一個Logger。Logger通常對應了程序的模塊名,比如聊天工具的圖形界面模塊可以這樣獲得它的Logger: LOG=logging.getLogger(”chat.gui”)
而核心模塊可以這樣: LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel):指定最低的日志級別,低于lel的級別將被忽略。debug是最低的內置級別,critical為最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或刪除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或刪除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以設置的日志級別
handler
handler
對象負責發送相關的信息到指定目的地。Python的日志系統有多種Handler可以使用。有些Handler可以把信息輸出到控制臺,有些Logger可以把信息輸出到文件,還有些 Handler可以把信息發送到網絡上。如果覺得不夠用,還可以編寫自己的Handler。可以通過
addHandler()方法添加多個多handler
Handler.setLevel(lel):指定被處理的信息級別,低于lel級別的信息將被忽略
Handler.setFormatter():給這個handler選擇一個格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或刪除一個filter對象
每個Logger可以附加多個Handler。接下來我們就來介紹一些常用的Handler:
logging.StreamHandler
使用這個Handler可以向類似與sys.stdout或者sys.stderr的任何文件對象(file object)輸出信息。它的構造函數是:
StreamHandler([strm])
其中strm參數是一個文件對象。默認是sys.stderr
logging.FileHandler
和StreamHandler類似,用于向一個文件輸出日志信息。不過FileHandler會幫你打開這個文件。它的構造函數是:
FileHandler(filename[,mode])
filename是文件名,必須指定一個文件名。
mode是文件的打開方式。參見Python內置函數open()的用法。默認是’a’,即添加到文件末尾。
logging.handlers.RotatingFileHandler
這個Handler類似于上面的FileHandler,但是它可以管理文件大小。當文件達到一定大小之后,它會自動將當前日志文件改名,然后創建 一個新的同名日志文件繼續輸出。比如日志文件是chat.log。當chat.log達到指定的大小之后,RotatingFileHandler自動把 文件改名為chat.log.1。不過,如果chat.log.1已經存在,會先把chat.log.1重命名為chat.log.2。。。最后重新創建 chat.log,繼續輸出日志信息。它的構造函數是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode兩個參數和FileHandler一樣。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes為0,意味著日志文件可以無限大,這時上面描述的重命名過程就不會發生。
backupCount用于指定保留的備份文件的個數。比如,如果指定為2,當上面描述的重命名過程發生時,原有的chat.log.2并不會被更名,而是被刪除。
logging.handlers.TimedRotatingFileHandler
這個Handler和RotatingFileHandler類似,不過,它沒有通過判斷文件大小來決定何時重新創建日志文件,而是間隔一定時間就 自動創建新的日志文件。重命名的過程與RotatingFileHandler類似,不過新的文件不是附加數字,而是當前時間。它的構造函數是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename參數和backupCount參數和RotatingFileHandler具有相同的意義。
interval是時間間隔。
when參數是一個字符串。表示時間間隔的單位,不區分大小寫。它有以下取值:
S 秒
M 分
H 小時
D 天
W 每星期(interval==0時代表星期一)
midnight 每天凌晨
文件自動截斷實例:
import logging from logging import handlerslogger = logging.getLogger(__name__) log_file = "timelog.log" fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3) #fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s') fh.setFormatter(formatter)logger.addHandler(fh)logger.warning("test1") logger.warning("test12") logger.warning("test13") logger.warning("test14")十、subprocess模塊(待定)
十一、json & pickle 模塊
用于序列化的兩個模塊json,用于字符串 和 python數據類型間進行轉換 pickle,用于python特有的類型 和 python的數據類型間進行轉換 Json模塊提供了四個功能:dumps、dump、loads、loadpickle模塊提供了四個功能:dumps、dump、loads、loadimport pickledate = {'k1':'123','k2':'hello'}str = pickle.dumps(date) # pickle.dumps 將數據通過特殊的形式轉換為只有python認識的字符串 print(str)with open('result.pk','w') as fp: # pickle.dump 將數據通過特殊的形式轉換為只有python認識的字符串并寫入文件pickle.dump(date,fp)import jsonstr1 = json.dumps(date) # json.dumps 將數據通過特殊形式轉換為所有程序語言都認識的字符串 print(str1)with open('result1.json','w') as fp: #json.dump 將數據通過特殊的形式轉換為只有python認識的字符串并寫入文件json.dump(date,fp)```總結
以上是生活随笔為你收集整理的Python自学——python的常用模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最近失业,不知道干什么好,随便乱写,无内
- 下一篇: 通讯频道:TOM续约Skype破镜重圆