這篇文章主要介紹Python標準庫都有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
操作系統接口
os 模塊提供了大量和操作系統進行交互的函數:
>>> import os
>>> os.getcwd() # 返回當前工作路徑
'C:\\Python37'
>>> os.chdir('/server/accesslogs') # 改變當前工作路徑
>>> os.system('mkdir today') # 調用系統shell自帶的mkdir命令
0請確保使用 import os 而不是 from os import *。第二種方法會導致 os.open() 覆蓋系統自帶的 open() 函數,這兩個函數的功能有很大的不同。
自帶的 dir() 和 help() 函數在使用大型模塊如 os 時能夠成為非常有用的交互工具:
>>> import os >>> dir(os) <返回一個包含os模塊所有函數的list> >>> help(os) <返回一個從os模塊docstring產生的手冊>
對于日常的文件或者目錄管理任務,shutil 模塊提供了更高層次的接口,可以讓用戶更容易地使用:
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'文件通配符
glob 模塊提供了一個函數,用于在目錄中進行通配符搜索,得到一個文件列表。
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']命令行參數
常見的工具類腳本經常需要處理命令行參數。 這些參數儲存在 sys 模塊的 argv 屬性中,作為一個列表存在。例如,以下是在命令行運行 python demo.py one two three 的結果輸出:
>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']
getopt 模塊使用 Unix 約定的 getopt() 函數處理 sys.argv 。更強大、靈活的命令行處理由 argparse 模塊提供。
錯誤輸出重定向和退出程序
sys 模塊有 stdin,stdout 和 stderr 這些屬性。后者在處理警告和錯誤信息時非常有用,就算 stdout 被重定向了,還是能看見錯誤信息:
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one退出程序最直接的方法是用 sys.exit()。
字符串匹配
re 模塊為字符串的進階處理提供了正則表達式的工具。對于復雜的匹配操作,正則表達式給出了簡潔有效的解決方案:
>>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat'
當只需要簡單的功能時,采用字符串的方法更簡潔易懂:
>>> 'tea for too'.replace('too', 'two')
'tea for two'數學庫
math 模塊可以訪問 C 語言編寫的浮點類型數學庫函數:
>>> import math >>> math.cos(math.pi / 4)0.70710678118654757 >>> math.log(1024, 2)10.0
random 模塊提供了進行隨機選擇的工具:
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # 不重復抽樣 [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # 隨機的 float 類型輸出 0.17970987693706186 >>> random.randrange(6) # 從 range(6) 的返回范圍內產生隨機數 4
網絡請求
有一大堆模塊可以訪問網絡并根據各自網絡協議來處理數據。其中最簡單的兩個分別是用于從 URL 獲取數據的 urllib.request 和用于發送郵件的 smtplib :
>>> from urllib.request import urlopen
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
... for line in response:
... line = line.decode('utf-8') # 解碼.
... if 'EST' in line or 'EDT' in line: # 查看是否是EST或EDT時間
... print(line)
<BR>Nov. 25, 09:43:32 PM EST
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()日期和時間
datetime 模塊提供了多種用于簡單處理和復雜處理日期和時間的類。支持日期時間的運算、時間解析、格式化輸出等,實現上重點優化了效率。模塊也支持了時區的概念。
>>> # 日期對象能非常方便的構建和輸出
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
>>> # 支持日期運算
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368以上是Python標準庫都有哪些的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。