python3-cookbook中每個小節以問題、解決方案和討論三個部分探討了Python3在某類問題中的最優解決方式,或者說是探討Python3本身的資料結構、函式、類等特性在某類問題上如何更好地使用,這本書對于加深Python3的理解和提升Python編程能力的都有顯著幫助,特別是對怎么提高Python程式的性能會有很好的幫助,如果有時間的話強烈建議看一下,
本文為學習筆記,文中的內容只是根據自己的作業需要和平時使用寫了書中的部分內容,并且文中的示例代碼大多直接貼的原文代碼,當然,代碼多數都在Python3.6的環境上都驗證過了的,不同領域的編程關注點也會有所不同,有興趣的可以去看全文,
python3-cookbook:https://python3-cookbook.readthedocs.io/zh_CN/latest/index.html
13.7 復制或者移動檔案和目錄
在使用shutil.copytree進行檔案夾的拷貝時,可以使用它的ignore引數來指定忽略的規則,引數值可以是一個函式,此函式接受一個目錄名和檔案名串列并回傳要忽略的名稱串列,也可以是shutil.ignore_patterns指定的忽略規則,
def ignore_pyc_files(dirname, filenames): return [name in filenames if name.endswith('.pyc')] shutil.copytree(src, dst, ignore=ignore_pyc_files) shutil.copytree(src, dst, ignore=shutil.ignore_patterns('*~', '*.pyc'))
13.8 創建和解壓歸檔檔案
如果只是簡單的解壓或者壓縮檔案,使用shutil.unpack_archive和shutil.make_archive就可以了,
>>> import shutil >>> shutil.unpack_archive('Python-3.3.0.tgz') >>> shutil.make_archive('py33','zip','Python-3.3.0') '/Users/beazley/Downloads/py33.zip' >>> >>># 支持的格式如下 >>> shutil.get_archive_formats() [('bztar', "bzip2'ed tar-file"), ('gztar', "gzip'ed tar-file"), ('tar', 'uncompressed tar file'), ('zip', 'ZIP file')] >>>
13.10 讀取組態檔
對于配置資料,特別是用戶配置資料,應該記錄在專門的組態檔中,比如ini檔案,對于ini檔案,可以使用內置的configparser模塊來進行讀寫,
這里只是列了些簡單的讀寫操作,關于configparser模塊更多資訊,可以查看官方檔案,或者可以參考下我的筆記:https://www.cnblogs.com/guyuyun/p/10965125.html
config.ini檔案內容如下:
; config.ini ; Sample configuration file [installation] library=%(prefix)s/lib include=%(prefix)s/include bin=%(prefix)s/bin prefix=/usr/local # Setting related to debug configuration [debug] log_errors=true show_warnings=False [server] port: 8080 nworkers: 32 pid-file=/tmp/spam.pid root=/www/root signature: ================================= Brought to you by the Python Cookbook =================================
讀取組態檔:
>>> from configparser import ConfigParser >>> cfg = ConfigParser() >>> cfg.read('config.ini') ['config.ini'] >>> cfg.sections() ['installation', 'debug', 'server'] >>> cfg.get('installation','library') '/usr/local/lib' >>> cfg.getboolean('debug','log_errors') True >>> cfg.getint('server','port') 8080 >>> cfg.getint('server','nworkers') 32 >>> print(cfg.get('server','signature')) \================================= Brought to you by the Python Cookbook \================================= >>>
修改組態檔:
>>> cfg.set('server','port','9000') >>> cfg.set('debug','log_errors','False') >>> import sys >>> cfg.write(sys.stdout) # 如果想將修改內容更新到檔案中,將這里的sys.stdout替換為對應檔案即可
13.15 啟動一個WEB瀏覽器
webbrowser模塊能被用來啟動一個瀏覽器,并且與平臺無關,默認使用系統默認的瀏覽器,其他支持的瀏覽器可以查看官方檔案,
>>> import webbrowser >>> webbrowser.open('http://www.python.org') # 以默認瀏覽器打開url True >>> webbrowser.open_new('http://www.python.org') # 在一個新的瀏覽器視窗打開url True >>> webbrowser.open_new_tab('http://www.python.org') # 在瀏覽器的新標簽中打開url True >>> c = webbrowser.get('firefox') # 使用指定的瀏覽器打開url >>> c.open('http://www.python.org') True
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/187939.html
標籤:Python
上一篇:python 初學者
