python內置模塊2

十5、shutil模塊

====================================================================python

shutil模塊是python爲咱們封裝的一個高級的高級的文件、文件夾、壓縮包 處理模塊,它本質上是調用open方法對文件進行讀寫。模塊相對比較簡單,記住幾個經常使用的方法便可。安全

shutil.copyfileobj(fsrc, fdst[, length])
將文件內容拷貝到另外一個文件中。這個是基本方法,其餘的拷貝方法都是在後臺調用這個方法。 函數

import shutil測試

shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))線程

shutil.copyfile(src, dst)
拷貝文件 debug

shutil.copyfile('f1.log', 'f2.log')日誌

 

shutil.copymode(src, dst)
僅拷貝權限。內容、組、用戶均不變 orm

shutil.copymode('f1.log', 'f2.log')xml

 

四、shutil.copystat(src, dst)
僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags對象

shutil.copystat('f1.log', 'f2.log')

 

五、 shutil.copy(src, dst)
拷貝文件和權限

shutil.copy('f1.log', 'f2.log')

 

六、shutil.copy2(src, dst)
拷貝文件和狀態信息 

shutil.copy2('f1.log', 'f2.log')

 

七、shutil.ignore_patterns(*patterns)

shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾。ignor_patterns是指忽略不拷貝的文件

shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

 

八、shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件

shutil.rmtree('folder1')

 

九、shutil.move(src, dst)
遞歸的去移動文件,它相似mv命令,其實就是重命名。 

shutil.move('folder1', 'folder3')

 

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

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

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

       ● base_name: 壓縮包的文件名,也能夠是壓縮包的路徑。只是文件名時,則保存至當前目錄,不然保存至指定路徑,
如:www                        =>保存至當前路徑
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/

        ● format: 壓縮包種類,「zip」, 「tar」, 「bztar」,「gztar」

       ●  root_dir: 要壓縮的文件夾路徑(默認當前目錄)

        ● owner: 用戶,默認當前用戶

       ●  group: 組,默認當前組

       ● logger: 用於記錄日誌,一般是logging.Logger對象

#將 /Users/wupeiqi/Downloads/test 下的文件打包放置當前程序目錄

import shutil

ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

   

#將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄

import shutil

ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

 

shutil 對壓縮包的處理本質上是調用 ZipFile 和 TarFile 兩個模塊來進行的,但封裝的比較簡單,不是很好用,建議仍是使用ZipFile 和 TarFile 模塊。

 

 

 

 

十6、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()   

要單獨解壓壓縮包內的某個文件就須要先得到壓縮包內的文件名列表。zipfile提供了一個namelist方法。

import zipfile

 

z = zipfile.ZipFile('laxi.zip', 'r')

ret = z.namelist()

print(ret)

z.close()

 

運行結果:

 

['testfile.bak', 'testfile.dat']

而後經過具體的文件名去解壓某個文件。zipfile提供了extract方法。

import zipfile

 

z = zipfile.ZipFile('laxi.zip', 'r')

z.extract("testfile.bak")

z.close()

 

 

 

 

十7、getpass模塊

===============================================================

getpass模塊很是簡單,它可以讓你在輸入密碼的時候不會在屏幕上顯示密碼,安全性更高。注意:在pycharm環境裏這個模塊用不了!

getpass模塊只有2個經常使用方法:getpass和getuser。參考下面的例子:

import getpass

pwd = getpass.getpass("請輸入密碼: ")  # 可代替input方法,接收用戶輸入的密碼

print(getpass.getuser())  # getuser方法會返回當前執行程序的用戶名

 

 

 

 

 

十8、bisect模塊

===================================================================

這是一個python內置的二分查找法模塊,模塊內只有4個方法:bisect_right、bisect_left、insort_right和insort_left。而後經過將bisect_right賦值給bisect,將insort_right賦值給insort實現向後兼容。實際使用中,是須要記住bisect和insort兩個方法便可。

bisect模塊的使用方法一般是:bisect.bisect(list,x),其中x表示要查找的值,list是一個默認已經排好序的列表。

bisect():返回值是x在列表中應處的位置下標,並不修改列表自己。

import bisect

 

x = 200

list1 = [1, 3, 6, 24, 55, 78, 454, 555, 1234, 6900]

ret = bisect.bisect(list1, x)

print("返回值: ", ret)

print("list1 = ", list1)

 

運行結果:

 

返回值:  6

list1 =  [1, 3, 6, 24, 55, 78, 454, 555, 1234, 6900]

insort():返回值是None,可是會將x插入到列表中生成新的列表。x插在它的大小排序所在位置。

import bisect

 

x = 200

list1 = [1, 3, 6, 24, 55, 78, 454, 555, 1234, 6900]

ret = bisect.insort(list1, x)

print("返回值: ", ret)

print("list1 = ", list1)

 

運行結果:

 

返回值:  None

list1 =  [1, 3, 6, 24, 55, 78, 200, 454, 555, 1234, 6900]

 

 

 

 

 

 

 

 

十9、fileinput模塊

===========================================================================

使用過python內置的open方法處理文件的同窗都知道,它沒有直接修改文件內容的方法。這個fileinput能夠幫助咱們輕鬆的實現文件內容的修改功能。fileinput模塊中的重要方法以下:

input([files[, inplace[, backup]])

  最重要的方法,用於遍歷打開的文件,inplace爲True的時候,會將修改寫入文件,backup爲True的時候會進行備份操做。

filename()

  返回當前文件的名字

lineno()

  返回當前(累計)的行數。同時處理多個文件時,行數會累計。

filelineno()

  返回當前文件的總行數。處理新文件時,行數會重置爲1,從新計數。

isfirstline()

  檢查當前行是不是文件的第一行

isstdin()

  檢查最後一行是否來自sys.stdin

nextfile()

  關閉當前文件,移動到下一個文件(fileinput是能夠同時處理多個文件的!)

close() 

  關閉整個文件鏈,結束迭代。

爲了演示fileinput的使用,假設編寫了以下的一個腳本,想要爲其代碼進行編號。爲了讓腳本在進行代碼編號後仍然可以正常運行,咱們只能在每一行的右側加上#來註釋行號。其中,咱們假定每一個代碼行最多有40個字符。具體代碼以下:

import fileinput                       

                                         

f = fileinput.input(inplace=True)       

for line in f:                         

    line = line.rstrip()                   

    num = fileinput.lineno()            

    print("%-40s # %2i" % (line, num))     

f.close()

  注意,只能使用rstrip,不能直接用strip,那樣會把左邊的縮進也給去掉了。

請在終端環境下,使用python fileinput_test.py fileinput_test.py的方式執行程序,結果以下:

import fileinput                         #  1

                                         #  2

f = fileinput.input(inplace=True)        #  3

for line in f:                           #  4

    line = line.rstrip()                 #  5

    num = fileinput.lineno()             #  6

    print("%-40s # %2i" % (line, num))   #  7

f.close()                                #  8

要當心使用inplace參數,它會修改文件。應該在不適用inplace設置的狀況下仔細測試本身的程序(這樣只會打印出結果),在確保程序工做正常後再修改文件。

 

 

 

 

 

 

二10、logging模塊

===========================================================================

python一樣提供logging日誌記錄模塊,如下是logging模塊配置參數

logging.basicConfig()函數中可經過具體參數來更改logging模塊默認行爲,可用參數有:

 

filename:用指定的文件名建立FiledHandler,這樣日誌會被存儲在指定的文件中。

filemode:文件打開方式,在指定了filename時使用這個參數,默認值爲「a」還可指定爲「w」。

format:指定handler使用的日誌顯示格式。

datefmt:指定日期時間格式。

level:設置rootlogger(後邊會講解具體概念)的日誌級別

stream:用指定的stream建立StreamHandler。能夠指定輸出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默認爲sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。

 

format參數中可能用到的格式化串:

%(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用戶輸出的消息

 

logging簡單測試

import logging 

logging.debug('debug message') 

logging.info('info message') 

logging.warning('warning message') 

logging.error('error message') 

logging.critical('critical message'

 

默認狀況下Python的logging模塊將日誌打印到了標準輸出中,且只顯示了大於等於WARNING級別的日誌,這說明默認的日誌級別設置爲WARNING(日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG),默認的日誌格式爲日誌級別:Logger名稱:用戶輸出消息。

logging自定義格式輸出

import logging

 

logging.basicConfig(level=logging.DEBUG,

                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

                    datefmt='%a, %d %b %Y %H:%M:%S',

                    filename='test.log',

                    filemode='w')

 

logging.debug('debug message')

logging.info('info message')

logging.warning('warning message')

logging.error('error message')

logging.critical('critical message')

生成test.log文件,內容以下

 

 

logging對象配置

import logging

logger = logging.getLogger()

# 建立一個handler,用於寫入日誌文件

fh = logging.FileHandler('test.log',encoding='utf-8')

 

# 再建立一個handler,用於輸出到控制檯

ch = logging.StreamHandler()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setLevel(logging.DEBUG)

 

fh.setFormatter(formatter)

ch.setFormatter(formatter)

logger.addHandler(fh) #logger對象能夠添加多個fh和ch對象

logger.addHandler(ch)

 

logger.debug('logger debug message')

logger.info('logger info message')

logger.warning('logger warning message')

logger.error('logger error message')

logger.critical('logger critical message')

logging庫提供了多個組件:Logger、Handler、Filter、Formatter。Logger對象提供應用程序可直接使用的接口,Handler發送日誌到適當的目的地,Filter提供了過濾日誌信息的方法,Formatter指定日誌顯示格式。另外,能夠經過:logger.setLevel(logging.Debug)設置級別,固然,也能夠經過

fh.setLevel(logging.Debug)單對文件流設置某個級別。

相關文章
相關標籤/搜索