Python常見模塊及其用法示例詳解
更新時間:2025年07月29日 09:40:09 作者:木子杳衫
模塊導入是Python開發(fā)中的一個重要環(huán)節(jié),但如果不小心,可能會遇到各種錯誤,這篇文章主要給大家介紹了關于Python常見模塊及其用法的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
1. 什么是模塊和包?
- 模塊是一個包含python代碼的文件(后綴名.py),內容可以包括函數、類、變量等
# 文件名為hello.py
def func():
print("hello world!")
func()
使用模塊
import hello
- 包是包含多個模塊的目錄,它通過__init__.py文件(可以是空文件)來標識這是一個Python包。
mypackage/
│── __init__.py
│── module1.py
│── module2.py
└── subpackage/
│── __init__.py
│── module3.py
使用包
from mypackage import module1,module2 from mypackage.subpackage import module3
2. 常見的模塊及其用法
本文主要講解模塊有:time random os sys json
- time 時間處理
- random 生成隨機數和實現隨機選擇功能
- os 操作系統(tǒng)交互
- sys 系統(tǒng)相關功能
- json JSON 數據處理
2.1 time
時間處理
概覽
| 方法 | 功能 | 示例 |
|---|---|---|
time() | 時間戳,1970年1月1日00:00:00 UTC至今的秒數 | 1753161307.4428105 |
ctime() | 獲取可讀的時間字符串 | “Tue Jul 22 13:15:07 2025" |
localtime() | 獲取結構化時間對象(包含年、月、日等字段) | time.struct_time(tm_year=2025, tm_mon=7, tm_mday=22, tm_hour=13, tm_min=15, tm_sec=7, tm_wday=1, tm_yday=203, tm_isdst=0) |
strftime("%Y-%m-%d %H:%M:%S",struct_time) | 時間格式化(字符串) | “2025-07-22 13:33:09” |
strptime(“2025-07-22”) | 時間解析 | “time.struct_time(tm_year=2025, tm_mon=7, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=203, tm_isdst=-1)” |
perf_counter()) | 精確計時(性能測試) | 耗時時間 |
sleep(2.5) | 程序暫停 | 停頓2.5秒 |
localtime() | 時間戳 -> struct_time | 時間類型轉化 |
mktime() | struct_time -> 時間戳 | 時間類型轉化 |
2.1.1 時間獲取方法
time.time()
- 功能:獲取當前的時間戳(1970年1月1日00:00:00 UTC至今的秒數)
- 示例:
import time print(time.time()) # 輸出:1753161307.4428105(當前時間)
time.ctime()
- 功能:獲取可讀的時間字符串
- 示例:
print(time.ctime()) # 輸出:“Tue Jul 22 13:15:07 2025”
time.localtime()
- 功能:獲取結構化時間對象(包含年、月、日等字段)
- 示例:
struct_time = time.localtime() print(struct_time.tm_year, struct_time.tm_mon,struct_time.tm_mday) # 輸出:2025 7 22
2.1.2 時間格式化與解析
time.strftime()
- 功能:時間格式化
- 示例:
struct_time = time.localtime()
formatted = time.strftime("%Y-%m-%d %H:%M:%S",struct_time)
# 輸出 2025-07-22 13:33:09
time.strptime()
- 功能:時間解析(字符串 -> struct_time)
- 示例:
parsed_time = time.strptime("2025-07-22", "%Y-%m-%d")
print(parsed_time)
# 輸出:
# time.struct_time(tm_year=2025, tm_mon=7, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=203, tm_isdst=-1)
2.1.3 程序計時與延遲
time.pref_counter()
- 功能:精確計時(性能測試)
- 示例:
start = time.perf_counter()
time.sleep(2)
end = time.perf_counter()
print(f"執(zhí)行耗時:{end - start:.4f}秒")
# 輸出:
# 執(zhí)行耗時:2.0003秒
time.sleep()
- 功能:程序暫停
- 示例:
start = int(time.time())
time.sleep(2)
end = int(time.time())
print(f"停頓{end - start:.2f}秒")
# 輸出:
# 停頓2.00秒
2.1.4 時間轉換
- 時間戳 -> struct_time
- 方法:time.localtime()
- 示例:
timestamp = time.time() ts_to_struct = time.localtime(timestamp) print(ts_to_struct) # 輸出: # time.struct_time(tm_year=2025, tm_mon=7, tm_mday=22, tm_hour=13, tm_min=50, tm_sec=49, tm_wday=1, tm_yday=203, tm_isdst=0)
struct_time -> 時間戳
- 方法:time.mktime()
- 示例:
struct_time = time.localtime() struct_to_ts = time.mktime(struct_time) print(struct_to_ts) # 輸出: # 1753163493.0
2.2 random
生成隨機數和實現隨機選擇功能
概覽
| 方法 | 功能 | 示例 |
|---|---|---|
random() | [0.0, 1.0) 的隨機浮點數 | 0.374501 |
uniform(a, b) | [a, b] 的隨機浮點數 | 7.823 |
randint(a, b) | [a, b] 的隨機整數 | 4 |
randrange(start, stop, step) | 指定范圍的隨機整數 | 45 |
choice(seq) | 序列中的隨機元素 | “green” |
choices(population, k) | 有放回抽樣 | [‘B’, ‘C’] |
sample(population, k) | 無放回抽樣 | [3, 1, 5] |
shuffle(seq) | 原地打亂序列 | [‘K’, ‘A’, ‘J’, ‘Q’] |
gauss(mu, sigma) | 高斯分布隨機數 | 0.735 |
seed(a) | 初始化隨機種子 | 固定隨機序列 |
getstate() / setstate() | 保存/恢復狀態(tài) | 重現隨機序列 |
2.2.1 基本隨機數
random.random()
- 功能:生成
[0.0, 1.0)之間的隨機浮點數。 - 示例:
import random print(random.random()) # 輸出:0.374501(隨機值)
控制小數位數
- 內置函數/四舍五入
round(random.random(), 3) # 默認 3 位小數- 格式化
formatted = f{random.random():.3f} # 默認 3 位小數
random.uniform(a, b)
- 功能:生成
[a, b]之間的隨機浮點數。 - 示例:
print(random.uniform(2, 10)) # 輸出:7.342(隨機浮點數)
2.2.2 隨機整數
random.randint(a, b)
- 功能:生成
[a, b]之間的隨機整數(包含兩端)。 - 示例:
print(random.randint(1, 10)) # 輸出:3
random.randrange(start, stop, step)
- 功能:從
range(start, stop, step)中隨機選擇一個整數[start, stop) 左開右閉。 - 示例:
print(random.randrange(0, 100, 5)) # 輸出:45(0,5,10,...,95 中的隨機數)
2.2.3 序列操作
random.choice(seq)
- 功能:從非空序列中隨機選擇一個元素。
- 示例:
colors = ['red', 'green', 'blue'] print(random.choice(colors)) # 輸出:'green'(隨機顏色)
random.choices(population, weights=None, k=1)
- 功能:從序列中有放回地隨機抽取
k個元素(可設置權重)。 - 示例:
result = random.choices(['A', 'B', 'C'], weights=[0.2, 0.5, 0.3], k=2) print(result) # 輸出:['B', 'C'](權重越高越可能被選中)
random.sample(population, k)
- 功能:從序列中無放回地隨機抽取
k個唯一元素。 - 示例:
numbers = [1, 2, 3, 4, 5] print(random.sample(numbers, 3)) # 輸出:[3, 1, 5](隨機不重復的3個數)
random.shuffle(seq)
- 功能:將序列原地隨機打亂(修改原序列)。
- 示例:
cards = ['A', 'K', 'Q', 'J'] random.shuffle(cards) print(cards) # 輸出:['K', 'A', 'J', 'Q'](順序隨機)
2.2.4 概率分布
random.gauss(mu, sigma)
- 功能:生成高斯分布(正態(tài)分布)的隨機數,
mu為均值,sigma為標準差。 - 示例:
print(random.gauss(0, 1)) # 輸出:0.735(標準正態(tài)分布中的隨機值)
random.expovariate(lambd)
- 功能:生成指數分布的隨機數,
lambd是事件發(fā)生率的倒數。 - 用途: 多用于建模隨機事件之間的時間間隔,尤其適合那些平均間隔已知但具體時間不確定的場景。
- 示例:
print(random.expovariate(1.0/5)) # 輸出:3.2(模擬平均每5秒發(fā)生一次的事件間隔)
2.2.5 隨機種子
random.seed(a=None)
- 功能:初始化隨機數生成器,相同種子生成相同隨機序列(用于可重復性)。
- 示例:
random.seed(42) # 固定種子 print(random.random()) # 輸出:0.6394(每次運行結果相同)
2.2.6 狀態(tài)管理
random.getstate()和random.setstate(state)
- 功能:保存/恢復隨機數生成器的內部狀態(tài)。
- 原理: 這是偽隨機數生成器的典型行為,用于保證生成的隨機數序列具有不可預測性和多樣性
- 示例:
state = random.getstate() # 保存當前狀態(tài) print(random.random()) # 隨機數1 random.setstate(state) # 恢復狀態(tài) print(random.random()) # 再次輸出相同的隨機數1
2.3 os
操作系統(tǒng)交互
概覽
| 方法 | 功能 | 備注 |
|---|---|---|
mkdir() | 創(chuàng)建單級目錄 | 存在時創(chuàng)建的目錄會報錯 |
makedirs() | 創(chuàng)建多級目錄 | exist_ok = True 已存在創(chuàng)建的目錄不會報錯 |
rename() | 重命名 | |
remove() | 刪除文件 | |
scandir() | 目錄遍歷 | |
walk() | 遞歸遍歷目錄 | |
os.path.join() | 路徑拼接 | |
os.path.dirname() 、os.path.basename()、os.path.splitext() | 路徑分解 | |
os.path.exists、os.path.isfile()、os.path.isdir() | 路徑檢查 | |
os.getcwd() | 獲取當前路徑 | |
os.chdir() | 修改工作目錄 | |
os.environ.get() | 獲取環(huán)境變量 | |
os.system() | 執(zhí)行系統(tǒng)命令 |
2.3.1 文件與目錄操作
創(chuàng)建目錄
- 方法:
os.mkdir()/os.makedirs() - 示例:
import os
os.mkdir("1") # 創(chuàng)建單級目錄 | 文件已存在會報錯
os.makedirs("test/1", exist_ok=True) # 創(chuàng)建多級目錄,exist_ok=True,當文件已存在時不報錯
- 文件操作
- 方法:
os.rename()/os.remove() - 示例:
import os
os.rename("old.txt","new.txt") # 重命名
os.remove("test/1.txt") # 刪除文件
- 目錄遍歷
- 方法:
os.scandir() - 示例:
import os
for entry in os.scandir("."): # . 遍歷當前目錄下的所有 文件 和 子目錄
if entry.is_file():
print("文件:",entry)
# 輸出:
# 文件: <DirEntry '1.py'>
2.3.2 路徑處理
路徑分解
- 方法:
os.path.dirname()|os.path.basename()|os.path.splitext() - 示例:
import os
path = "/home/user/documents/report.txt"
# 獲取路徑組成部分
dir_path = os.path.dirname(path) # 目錄路徑: "/home/user/documents"
file_name = os.path.basename(path) # 完整文件名: "report.txt"
file_root, file_ext = os.path.splitext(file_name) # 分離主名和擴展名: ("report", ".txt")
# 完整路徑拆分
head, tail = os.path.split(path) # ("/home/user/documents", "report.txt")
路徑拼接
- 方法:
os.path.join() - 示例:
full_path = os.path.join("dir","subdir","file.txt")
路徑檢查
- 方法:
os.path.exists()|os.path.isfile()|os.path.isdir() - 示例:
print(os.path.exists("1.txt")) # 是否存在
print(os.path.isfile("1.txt")) # 是否是文件
print(os.path.isdir("1.txt")) # 是否是目錄
# 輸出答案(根據個人本地要查詢的文件為主)
# True
# True
# False
2.3.3 系統(tǒng)信息與環(huán)境
os.getcwd()
- 功能:獲取當前工作目錄
- 示例:
cwd = os.getcwd()
os.chdir()
- 功能:修改工作目錄
- 示例:
cwd = os.chdir("/new/path")
os.environ.get()
- 功能:獲取環(huán)境變量
- 示例:
home_dir = os.enciron.get("HOME","default") # 查找 HOME 值,沒有則返回默認值 default
print(home_dir)
os.system()
- 功能:執(zhí)行系統(tǒng)命令
- 示例:
os.system("ls -l")
2.4 sys
系統(tǒng)相關功能
概覽
| 方法 | 功能 | 備注 |
|---|---|---|
sys.argv | 獲取命令行參數 | |
sys.stdout | 重定向輸出 | |
sys.stdin.readline().strip() | 讀取標準輸入 | |
sys.version | 獲取Python版本信息 | |
sys.path | 獲取模塊搜索路徑 | |
sys.exit(1) | 退出程序并返回狀態(tài)碼 | 非0狀態(tài)碼表示異常退出 |
sys.stdout.flush() | 刷新輸出緩沖區(qū) | 確保立即顯示 |
2.4.1 命令行參數處理
sys.argv
- 功能:獲取命令行參數
- 示例:
# 假設執(zhí)行:python scripts.py arg1 arg2 --option=value
print(sys.argv) # ['script.py', 'arg1', 'arg2', '--option=value']
# 實際應用:處理命令行選項
if len()sys.argv) > 1:
action = sys.argv[1] # arg1
if action == "start":
print("")
elif action == "stop":
print("")
2.4.2 標準輸入/輸出控制
sys.stdout
- 功能:重定向輸出
- 示例:
with open('1.txt','w',encoding="utf-8-sig") as f:
sys.stdout = f # 重定向標準輸出到文件
print("這條信息將寫入文件")
sys.stdout = sys._stdout__ # 恢復標準輸出
# 會將print中的內容寫進 1.txt文件內
sys.stdin.readline().strip()
- 功能:讀取標準輸入
- 示例:
print("請輸入內容:")
user_input = sys.stdin.readline().strip()
print(f"您輸入了:{user_input}")
# 輸出:
"""
請輸入內容:
1 2 3
您輸入了:1 2 3
"""
2.4.3 系統(tǒng)信息與配置
sys.version
- 功能:獲取
Python版本信息 - 示例:
print(sys.version) # 輸出 """ 3.11.9 (tags/v3.11.9:de54cf5, Apr 2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)] """
sys.path
- 功能:獲取模塊搜索路徑
- 示例:
print(sys.path) # 輸出列表形式,包含Python查找模塊的路徑
sys.platform
- 功能:獲取操作系統(tǒng)平臺
- 示例:
print(sys.platform) # 'win32', 'linux', 'darwin' (macOS) # 輸出 """ win32 """
2.4.4 程序流程控制
sys.exit(n)
- 功能:退出程序并返回狀態(tài)碼(n=0時,正常退出;n=1《或是其它數字》時表示異常退出)
- 場景:通常用于腳本或程序中發(fā)生錯誤時提前退出,表示異常終止
- 示例:
if error_occurred: sys.exit(1) # 非0狀態(tài)碼表示異常退出
sys.stdout.flush()
print("處理中...", end="")
sys.stdout.flush()
# 執(zhí)行耗時操作...
print("完成!")
2.5 json
JSON 數據處理
概覽
| 方法 | 功能 |
|---|---|
json.dumps() | Python -> JSON字符串 |
json.loads() | JSON字符串 -> Python |
json.dump | 寫入JSON文件 |
json.load() | 讀取JSON文件 |
2.5.1 基本序列化與反序列化
Python -> JSON字符串
- 方法:
json.dumps() - 示例:
import json
data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading"],
"is_student": False,
}
json_str = json.dumps(data, indent=2)
print(json_str)
# 輸出:
"""
{
"name": "Alice",
"age": 30,
"hobbies": [
"reading",
"hiking"
],
"is_student": false
}
"""
JSON字符串 -> Python
- 方法:
json.loads() - 示例:
restored_data = json.loads(json_str) print(restored_data["name"]) # "Alice"
2.5.2 文件讀寫操作
json.dump()
- 功能:寫入JSON文件
- 示例:
with open("data.json", "w") as f:
json.dump(data, f, indent=4) # 控制為 4 縮進空格
json.load()
- 功能:讀取JSON文件
- 示例:
with open("data.json") as f:
loaded_data = json.load(f)
2.5.3 高級序列化控制
# 處理自定義對象
class User:
def __init__(self, name, age):
self.name = name
self.age = age
# 自定義序列化方法
def user_encoder(obj):
if isinstance(obj, User): # 判斷 obj 是否是 User 的實例
return {"name": obj.name, "age": obj.age}
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
user = User("Bob", 40)
user_json = json.dumps(user, default=user_encoder) # {"name": "Bob", "age": 40}
# 自定義反序列化方法
def user_decoder(dct):
if "name" in dct and "age" in dct:
return User(dct["name"], dct["age"])
return dct
restored_user = json.loads(user_json, object_hook=user_decoder)
print(restored_user.name) # "Bob"
```
總結
到此這篇關于Python常見模塊及其用法示例詳解的文章就介紹到這了,更多相關Python常見模塊用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python正則表達式去掉數字中的逗號(python正則匹配逗號)
在處理自然語言時123,000,000如果以標點符號分割,就會出現問題,好好的一個數字就被逗號肢解了,因此可以先下手把數字處理干凈(逗號去掉)2013-12-12
開源軟件包和環(huán)境管理系統(tǒng)Anaconda的安裝使用
Anaconda是一個用于科學計算的Python發(fā)行版,支持 Linux, Mac, Windows系統(tǒng),提供了包管理與環(huán)境管理的功能,可以很方便地解決多版本python并存、切換以及各種第三方包安裝問題。2017-09-09
手把手教你快速安裝gpu版本的pytorch(詳細圖文教程)
在Windows?10上安裝PyTorch時,通常默認安裝的是CPU版本,且下載速度較慢,本文提供了一個詳細的安裝指南,包括如何檢查CUDA版本、選擇合適的PyTorch、torchvision和torchaudio版本,并通過pip而非conda進行安裝,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-09-09

