學(xué)習(xí) Python 的基礎(chǔ):Python 最常用的 18 個(gè)內(nèi)置模塊
在 Python 開發(fā)中,基礎(chǔ)模塊(內(nèi)置模塊)是標(biāo)準(zhǔn)庫的核心組成部分,直接內(nèi)置于 Python 解釋器中,無需額外安裝即可使用。
它們?yōu)殚_發(fā)者提供了一系列通用的、跨平臺(tái)的功能,覆蓋了從系統(tǒng)交互到數(shù)據(jù)處理的廣泛需求。以下是常用的18個(gè)模塊,建議收藏:

1. os(操作系統(tǒng)交互)
用途:操作系統(tǒng)交互(文件/目錄管理、環(huán)境變量等)。
常用函數(shù):os.listdir(), os.mkdir(), os.path.join().
import os
# 列出當(dāng)前目錄下的文件和文件夾
print(os.listdir())
# 創(chuàng)建新目錄
os.mkdir("new_folder")
# 拼接路徑(跨平臺(tái)兼容)
path = os.path.join("folder", "subfolder", "file.txt")2. sys(系統(tǒng)參數(shù))
用途:訪問系統(tǒng)參數(shù)(命令行參數(shù)、Python解釋器等)。
常用:sys.argv, sys.exit(), sys.path.
import sys
# 獲取命令行參數(shù)(例如:python script.py arg1 arg2)
print(sys.argv)  # 輸出:['script.py', 'arg1', 'arg2']
# 退出程序并返回狀態(tài)碼
sys.exit(0)  # 0 表示正常退出3. datetime(日期時(shí)間)
用途:日期和時(shí)間處理。
常用類:datetime.datetime, datetime.timedelta.
from datetime import datetime, timedelta
# 當(dāng)前時(shí)間
now = datetime.now()
# 格式化輸出:2025-04-17 19:30:00
print(now.strftime("%Y-%m-%d %H:%M:%S"))  
# 時(shí)間加減(增加1天)
tomorrow = now + timedelta(days=1)4. time(時(shí)間操作)
用途:時(shí)間相關(guān)操作(計(jì)時(shí)、休眠等)。
常用:time.sleep(), time.time().
import time
# 計(jì)時(shí)開始
start = time.time()
# 休眠2秒
time.sleep(2)
# 計(jì)算耗時(shí)  輸出:耗時(shí):2.00秒
print(f"耗時(shí):{time.time() - start:.2f}秒")5. math(數(shù)學(xué)運(yùn)算)
用途:數(shù)學(xué)運(yùn)算(三角函數(shù)、對(duì)數(shù)等)。
常用函數(shù):math.sqrt(), math.sin(), math.pi.
import math
# 平方根
print(math.sqrt(16))  # 4.0
# 圓周率
print(math.pi)  # 3.1415926535897936. random(隨機(jī)數(shù))
用途:生成隨機(jī)數(shù)和隨機(jī)操作。
常用:random.randint(), random.choice().
import random
# 生成1到10的隨機(jī)整數(shù)
print(random.randint(1, 10))
# 從列表中隨機(jī)選擇一個(gè)元素
colors = ["red", "green", "blue"]
print(random.choice(colors))7. json(JSON處理)
用途:JSON 數(shù)據(jù)編碼與解析。
常用函數(shù):json.dumps(), json.loads().
import json
# 將字典轉(zhuǎn)換為JSON字符串
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
print(json_str)  # {"name": "Alice", "age": 30}
# 解析JSON字符串
parsed_data = json.loads(json_str)
print(parsed_data["name"])  # Alice8. re(正則表達(dá)式)
用途:正則表達(dá)式匹配。
常用:re.search(), re.findall(), re.sub().
import re
text = "電話:123-456-7890"
# 查找所有數(shù)字
numbers = re.findall(r'\d+', text)
print(numbers)  # ['123', '456', '7890']
# 替換字符
new_text = re.sub(r'-', '', text)
print(new_text)  # 電話:12345678909. collections(高級(jí)數(shù)據(jù)結(jié)構(gòu))
用途:高級(jí)數(shù)據(jù)結(jié)構(gòu)(命名元組、默認(rèn)字典等)。
常用類:collections.defaultdict, collections.Counter.
from collections import defaultdict, Counter
# 默認(rèn)字典(自動(dòng)初始化鍵)
dd = defaultdict(int)
dd["apple"] += 1
print(dd["apple"])  # 1
# 統(tǒng)計(jì)元素出現(xiàn)次數(shù)
words = ["apple", "banana", "apple"]
counter = Counter(words)
print(counter)  # Counter({'apple': 2, 'banana': 1})10. argparse(命令行解析)
用途:命令行參數(shù)解析。
核心類:argparse.ArgumentParser.
import argparse
# 創(chuàng)建解析器
parser = argparse.ArgumentParser(description="示例程序")
parser.add_argument("--input", help="輸入文件路徑")
parser.add_argument("--verbose", action="store_true", help="詳細(xì)模式")
# 解析參數(shù)
args = parser.parse_args()
if args.verbose:
    print("詳細(xì)模式已開啟")11. logging(日志記錄)
用途:日志記錄(調(diào)試、錯(cuò)誤追蹤等)。
常用函數(shù):logging.basicConfig(), logging.getLogger().
import logging
# 配置日志格式和級(jí)別
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
# 記錄日志
logging.info("程序啟動(dòng)")
logging.error("發(fā)生錯(cuò)誤!")12. subprocess(執(zhí)行外部命令)
用途:執(zhí)行外部命令(啟動(dòng)進(jìn)程、管道交互)。
常用函數(shù):subprocess.run().
import subprocess
# 執(zhí)行系統(tǒng)命令(例如:列出文件)
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)13. socket(網(wǎng)絡(luò)通信)
用途:網(wǎng)絡(luò)通信(TCP/UDP 編程)。
核心類:socket.socket.
import socket
# 創(chuàng)建TCP客戶端
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("www.httpbin.org", 80))
client.send(b"GET /get HTTP/1.1\r\nHost: httpbin.org\r\n\r\n")
response = client.recv(4096)
print(response.decode())
client.close()14. urllib(URL請(qǐng)求)
用途:處理 URL 請(qǐng)求(HTTP/HTTPS 客戶端)。
子模塊:urllib.request, urllib.parse.
from urllib.request import urlopen
from urllib.parse import urlencode
# 發(fā)送HTTP GET請(qǐng)求
response = urlopen("https://www.httpbin.org/get")
print(response.read().decode()[:100])  # 輸出前100個(gè)字符
# 編碼URL參數(shù)
params = urlencode({"q": "python", "page": 2})
print(params)  # q=python&page=215. csv(CSV文件讀寫)
用途:讀寫 CSV 文件。
常用類:csv.reader, csv.writer.
import csv
# 寫入CSV文件
with open("data.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 30])
# 讀取CSV文件
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)  # ['Name', 'Age'], ['Alice', '30']16. pickle(對(duì)象序列化)
用途:Python 對(duì)象序列化與反序列化。
常用函數(shù):pickle.dump(), pickle.load().
import pickle
# 序列化對(duì)象到文件
data = {"a": 1, "b": 2}
with open("data.pkl", "wb") as f:
    pickle.dump(data, f)
# 反序列化
with open("data.pkl", "rb") as f:
    loaded_data = pickle.load(f)
print(loaded_data)  # {'a': 1, 'b': 2}17. sqlite3(SQLite數(shù)據(jù)庫)
用途:操作 SQLite 數(shù)據(jù)庫。
核心類:sqlite3.Connection, sqlite3.Cursor.
import sqlite3
# 連接數(shù)據(jù)庫并創(chuàng)建表
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)"
cursor.execute(sql)
# 插入數(shù)據(jù)
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
conn.commit()
# 查詢數(shù)據(jù)
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())  # [(1, 'Alice')]
conn.close()18. hashlib(哈希算法)
用途:哈希算法(MD5、SHA256 等)。
常用函數(shù):hashlib.md5(), hashlib.sha256().
import hashlib
# 計(jì)算字符串的MD5哈希值
text = "Hello, World!"
md5 = hashlib.md5(text.encode()).hexdigest()
print(md5)  # 65a8e27d8879283831b664bd8b7f0ad4
# 計(jì)算文件的SHA256
with open("file.txt", "rb") as f:
    sha256 = hashlib.sha256(f.read()).hexdigest()
print(sha256)使用場(chǎng)景示例
- 數(shù)據(jù)處理:json, csv, pickle, collections.
 - 系統(tǒng)腳本:os, sys, argparse, subprocess.
 - 網(wǎng)絡(luò)編程:socket, urllib.
 - 工具開發(fā):logging, datetime, random.
 
總結(jié)
Python 基礎(chǔ)模塊是開發(fā)者的“瑞士軍刀”,覆蓋了日常開發(fā)中的高頻需求:
- 快速解決 80% 的常見問題(如文件操作、數(shù)據(jù)處理)。
 - 寫出更簡潔、高效、可維護(hù)的代碼。
 - 為學(xué)習(xí)更復(fù)雜的框架和庫(如 Django、NumPy)打下堅(jiān)實(shí)基礎(chǔ)。
 















 
 
 










 
 
 
 