Python標準庫一覽

過了即是客發表於2017-04-01

Python官方教程的最後一個部分就是標準庫概覽,在這裡我們瀏覽一下標準庫,瞭解一下Python標準庫包含了哪些功能。

作業系統和檔案操作

os

os模組包含了當前作業系統的抽象,我們可以利用os模組對作業系統進行各種訪問。下面使用os模組的幾個方法和屬性,訪問了當前指令碼路徑、作業系統名以及整個環境變數。

print(`--------------os--------------`)

import os
print(f`current dir:{os.curdir}`)
print(f`os name:{os.name}`)
print(f`os path:{os.environ}`)
print(f`os linesep:{os.linesep}`)

shutil

該模組包含了檔案和資料夾的通用工具、包括移動、複製檔案和資料夾等等。

print(`--------------shutil--------------`)
import shutil

hosts_file = r`C:WindowsSystem32driversetchosts`
dest_file = r`D:Desktophosts.txt`

shutil.copy2(hosts_file, dest_file)

glob

glob模組提供了萬用字元來選擇檔案。

print(`--------------glob--------------`)
import glob

source_files = glob.glob(`*.py`)
print(source_files)

sys

sys模組的argv屬性可以獲取當前Python指令碼執行時的命令列引數。

print(`--------------sys--------------`)
import sys

print(sys.argv)

sys模組還有幾個屬性,用於向標準輸入、輸出、錯誤流寫入和讀取資料。例如下面的例子將向標準錯誤流輸出了一些資訊。

sys.stderr.write(`This is a error
`)

正規表示式

re模組用於處理正規表示式。

下面的例子查詢所有以f開頭的單詞。

print(`--------------re--------------`)
import re

long_sentence = ```
When symlinks is false, if the file pointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this option has no effect on platforms that don’t support os.symlink().
```

results = re.findall(r`fw+`, long_sentence)
print(results)

數學計算

math

math模組包含了很多數學計算的函式。如果需要高階數學計算,可以查閱awesome-python專案查詢流行的數學計算模組。

print(`--------------math--------------`)
import math

print(f`PI is {math.pi}`)
print(f`e is {math.e}`)

random

random模組包含了一些生成隨機數的函式。


print(`--------------random--------------`)
import random

for i in range(1, 6):
    print(random.choice([1, 2, 3, 4, 5]), end=` `)
print()

for i in range(1, 6):
    print(random.randrange(1, 100), end=` `)
print()

for i in range(1, 6):
    print(random.randint(1, 10), end=` `)
print()

for i in range(1, 6):
    print(random.uniform(1, 10), end=` `)
print()

list1 = [1, 2, 3, 4, 5]
random.shuffle(list1)
print(f`打亂之後:{list1}`)

statistics

statistics模組可用於基本的統計。

print(`--------------statistics--------------`)
import statistics

data = [1, 2, 3, 4, 5, 6, 7, 4, 5, 6, 2, 3, 4, 4, 4, 4]

print(f`平均數:{statistics.mean(data)}`)
print(f`中位數:{statistics.median(data)}`)
print(f`方差:{statistics.variance(data)}`)
print(f`標準差:{statistics.stdev(data)}`)
print(f`眾數:{statistics.mode(data)}`)

網路

urllib.requesturllib.smtp是處理網路的兩個包,用於發起網路請求以及收發電子郵件。

print(`--------------urllib.request--------------`)
import urllib.request

with urllib.request.urlopen(`http://www.baidu.com`) as web:
   for line in web:
       print(line.decode(`UTF8`),end=``)

日期時間

datetime模組包含了日期時間的處理。

print(`--------------datetime--------------`)
import datetime

today = datetime.date.today()

now = datetime.datetime.today()

print(f`today:{today}`)
print(f`now:{now}`)

my_age = today - datetime.date(1994, 7, 7)
print(f`my age:{my_age.days/365}`)

資料壓縮

zlib模組可用於資料壓縮。

print(`--------------zlib--------------`)

import zlib

data = b`aaaaa bbbbbbb cccccc dddddddd`

compressed = zlib.compress(data)
print(f`data length:{len(data)}, compressed length:{len(compressed)}`)

print(f`compressed:{str(compressed)}`)
data = zlib.decompress(compressed)
print(f`data:{str(data)}`)

其他模組

標準庫的模組有很多,這裡不介紹了。有興趣的請直接檢視相應資料。

timeitprofilepstats模組可用於效能測量。

doctestunittest用於進行測試。

jsonxmlcsv等模組可以處理相應資料。

sqlite3模組用於處理Sqlite3嵌入式資料庫。

gettextlocalecodecs等模組用於國際化。


相關文章