Python 24個(gè)常用模塊編程必備知識庫
更新時(shí)間:2026年03月12日 09:00:17 作者:東眠的魚
本文給大家分享Python 24個(gè)常用模塊編程必備知識庫,本文通過實(shí)例代碼給介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
1.os - 系統(tǒng)交互大師
import os # 查看當(dāng)前工作目錄
print(os.getcwd()) # 創(chuàng)建新目錄
os.mkdir('new_folder') # 列出指定目錄下的文件和子目錄
for item in os.listdir('.'):
print(item)
- os模塊是Python與操作系統(tǒng)對話的橋梁,讓你輕松進(jìn)行文件和目錄操作,如獲取當(dāng)前工作目錄、創(chuàng)建新目錄、列出目錄內(nèi)容等。
2.sys - 程序運(yùn)行內(nèi)幕探索者
import sys # 輸出Python版本信息 print(sys.version) # 打印命令行參數(shù) for arg in sys.argv: print(arg)
- sys模塊提供了訪問和控制Python解釋器運(yùn)行時(shí)環(huán)境的方法,比如查看Python版本、獲取命令行參數(shù)等,幫你洞察程序內(nèi)部運(yùn)作機(jī)制。
3.datetime - 時(shí)間管理專家
from datetime import datetime, timedelta # 獲取當(dāng)前日期時(shí)間 now = datetime.now() print(now) # 計(jì)算未來日期 future_date = now + timedelta(days=30) print(future_date)
- datetime模塊讓處理日期和時(shí)間變得簡單直觀,你可以獲取當(dāng)前時(shí)間、計(jì)算時(shí)間間隔、進(jìn)行日期格式化等,是編寫與時(shí)間相關(guān)的程序不可或缺的好幫手。
4.math - 數(shù)學(xué)運(yùn)算寶庫
import math # 計(jì)算圓面積 radius = 5 area = math.pi * radius ## 2 print(area) # 計(jì)算最大公約數(shù) num1, num2 = ?, 21 gcd = math.gcd(num1, num2) print(gcd)
- math模塊封裝了大量數(shù)學(xué)函數(shù)和常量,如求平方根、計(jì)算圓周率、求最大公約數(shù)等,滿足你的數(shù)學(xué)運(yùn)算需求。
5.random - 隨機(jī)數(shù)生成魔術(shù)師
import random # 生成一個(gè)[0, 1)之間的隨機(jī)浮點(diǎn)數(shù) rand_float = random.random() print(rand_float) # 隨機(jī)從列表中選取一個(gè)元素 choices = ['apple', 'banana', 'orange'] random_choice = random.choice(choices) print(random_choice)
- random模塊負(fù)責(zé)生成各種類型的隨機(jī)數(shù),以及對列表等容器進(jìn)行隨機(jī)抽樣,為你的程序添加不確定性,模擬真實(shí)世界的隨機(jī)行為。
6.csv - 數(shù)據(jù)導(dǎo)出導(dǎo)入能手
import csv
# 寫入CSV文件
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', 25])
# 讀取CSV文件
with open('data.csv', newline='') as file:
reader = csv.reader(file)
for row in reader:
print(row)
- csv模塊簡化了CSV(逗號分隔值)文件的讀寫操作,無論是保存數(shù)據(jù)還是分析外部數(shù)據(jù)源,它都是你的得力助手。
7.json - JSON數(shù)據(jù)處理好幫手
import json
# 將Python對象轉(zhuǎn)換為JSON字符串
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)
print(json_str)
# 從JSON字符串解析回Python對象
loaded_data = json.loads(json_str)
print(loaded_data)
- json模塊用于序列化和反序列化JSON數(shù)據(jù),使得Python程序能夠輕松與使用JSON格式的Web服務(wù)或其他應(yīng)用程序交換數(shù)據(jù)。
8.requests - 網(wǎng)絡(luò)請求小飛俠
import requests
# 發(fā)送GET請求并打印響應(yīng)內(nèi)容
response = requests.get('https://api.github.com')
print(response.text)
- requests庫簡化了HTTP請求的發(fā)送過程,無論是GET、POST還是其他方法,只需幾行代碼就能實(shí)現(xiàn),大大提升了網(wǎng)絡(luò)通信效率。
9.pandas - 數(shù)據(jù)分析與處理巨擘
import pandas as pd
# 從CSV文件加載數(shù)據(jù)到DataFrame
df = pd.read_csv('data.csv')
# 查看前5行數(shù)據(jù)
print(df.head())
- pandas庫提供了強(qiáng)大的數(shù)據(jù)結(jié)構(gòu)DataFrame,用于高效地進(jìn)行數(shù)據(jù)分析、清洗、統(tǒng)計(jì)和可視化,是Python數(shù)據(jù)科學(xué)領(lǐng)域的核心工具之一。
10.numpy - 科學(xué)計(jì)算與數(shù)組操作神器
import numpy as np # 創(chuàng)建一個(gè)2x2的數(shù)組 arr = np.array([[1, 2], [3, 4]]) print(arr) # 計(jì)算數(shù)組元素之和 sum_arr = np.sum(arr) print(sum_arr)
- numpy庫提供高性能的多維數(shù)組對象和豐富的數(shù)學(xué)函數(shù),是進(jìn)行數(shù)值計(jì)算、機(jī)器學(xué)習(xí)、信號處理等領(lǐng)域開發(fā)的基礎(chǔ)庫。
11.matplotlib - 數(shù)據(jù)可視化魔法師
import matplotlib.pyplot as plt # 繪制簡單的折線圖 plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.show()
- matplotlib庫用于創(chuàng)建靜態(tài)、動態(tài)、交互式的圖表,如折線圖、散點(diǎn)圖、柱狀圖等,是Python數(shù)據(jù)可視化的首選工具。
12.scipy - 科學(xué)計(jì)算全方位助手
from scipy.optimize import minimize # 定義目標(biāo)函數(shù) def f(x): return x## 2 + 10*np.sin(x) # 使用優(yōu)化算法找到最小值 result = minimize(f, x0=0) print(result.x)
- scipy庫包含眾多科學(xué)計(jì)算工具箱,如最優(yōu)化、插值、積分、信號處理、統(tǒng)計(jì)分析等,極大地?cái)U(kuò)展了Python在科學(xué)計(jì)算領(lǐng)域的能力。
13.re - 正則表達(dá)式獵手
import re
# 使用正則表達(dá)式匹配郵箱地址
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
text = 'Contact me at alice@example.com or bob@gmail.com'
matches = re.findall(pattern, text)
print(matches)
- re模塊實(shí)現(xiàn)了正則表達(dá)式的支持,讓你能夠靈活、高效地進(jìn)行文本模式匹配、查找、替換等操作。
14.threading - 多線程任務(wù)執(zhí)行者
import threading
# 定義線程任務(wù)
def thread_task(name):
print(f"Thread {name} started.")
# ... 執(zhí)行任務(wù) ...
print(f"Thread {name} finished.")
# 創(chuàng)建并啟動兩個(gè)線程
t1 = threading.Thread(target=thread_task, args=("Thread 1",))
t2 = threading.Thread(target=thread_task, args=("Thread 2",))
t1.start()
t2.start()
# 等待所有線程完成
t1.join()
t2.join()
print("All threads finished.")
- threading模塊支持多線程編程,使程序能夠在同一時(shí)刻執(zhí)行多個(gè)任務(wù),提高程序并發(fā)性能和響應(yīng)速度。
15.timeit - 代碼性能測量儀
import timeit
# 測試代碼塊執(zhí)行時(shí)間
setup = "import math"
statement = "math.factorial(100)"
elapsed_time = timeit.timeit(setup=setup, stmt=statement, number=1000)
print(f"Average execution time: {elapsed_time/1000:.6f} seconds")
- timeit模塊提供了一種簡便的方法來測量小段代碼的執(zhí)行時(shí)間,幫助開發(fā)者評估代碼性能,進(jìn)行優(yōu)化。
16.unittest - 單元測試守護(hù)神
import unittest class TestMathFunctions(unittest.TestCase): def test_factorial(self): self.assertEqual(math.factorial(5), 120) def test_gcd(self): self.assertEqual(math.gcd(18, 24), 6) if __name__ == '__main__': unittest.main()
- unittest模塊是Python標(biāo)準(zhǔn)庫中的單元測試框架,通過編寫測試用例來確保代碼的正確性和穩(wěn)定性。
17.argparse - 命令行參數(shù)解析器
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
- argparse模塊用于創(chuàng)建用戶友好的命令行接口,輕松處理程序接受的命令行參數(shù)。
18.logging - 程序日志記錄員
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("This is an informative message.")
logger.warning("Watch out! This might be a problem.")
- logging模塊提供了通用的日志記錄系統(tǒng),方便程序在運(yùn)行過程中記錄調(diào)試信息、異常情況等,便于問題排查和跟蹤。
19.sqlite3 - 輕量級數(shù)據(jù)庫連接器
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
cursor.execute("INSERT INTO stocks VALUES ('202.jpg', 'BUY', 'RHAT', 100, 35.14)")
conn.commit()
conn.close()
- sqlite3模塊是Python內(nèi)置的SQLite數(shù)據(jù)庫驅(qū)動,允許程序直接操作SQLite數(shù)據(jù)庫,進(jìn)行數(shù)據(jù)存儲、查詢等操作。
20.hashlib - 哈希函數(shù)計(jì)算者
import hashlib message = "Hello, world!".encode() digest = hashlib.sha256(message).hexdigest() print(digest)
- hashlib模塊提供了多種安全的哈希函數(shù),如SHA-256,用于生成消息摘要或校驗(yàn)數(shù)據(jù)完整性。
21.xml.etree.ElementTree - XML解析與生成伙伴
import xml.etree.ElementTree as ET
root = ET.Element("root")
child = ET.SubElement(root, "child", name="element1")
ET.SubElement(child, "grandchild").text = "Some text"
tree = ET.ElementTree(root)
tree.write("output.xml")
- xml.etree.ElementTree模塊提供了處理XML文檔的API,包括解析、構(gòu)建、搜索XML樹等功能。
22.shutil - 文件與目錄操作好伙伴
import shutil
shutil.copyfile('source.txt', 'destination.txt')
shutil.move('old_file.txt', 'new_file.txt')
shutil.rmtree('directory_to_remove')
- shutil模塊提供了高級文件和目錄操作功能,如復(fù)制、移動文件,刪除目錄及其內(nèi)容等。
23.itertools - 生成器與迭代器魔法工廠
import itertools combinations = itertools.combinations(range(4), 2) for combo in combinations: print(combo)
- itertools模塊包含了一系列高效且內(nèi)存友好的迭代器函數(shù),如生成組合、排列、無限序列等,極大豐富了Python的循環(huán)結(jié)構(gòu)。
24.functools - 高級函數(shù)工具箱
import functools @functools.lru_cache(maxsize=32) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) print(fib(10))
- functools模塊提供了許多用于處理函數(shù)的工具,如裝飾器、高階函數(shù)等,有助于編寫更簡潔、更高效的代碼。
總結(jié)
到此這篇關(guān)于Python 24個(gè)常用模塊編程必備知識庫的文章就介紹到這了,更多相關(guān)Python常用模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)桶排序與快速排序算法結(jié)合應(yīng)用示例
這篇文章主要介紹了Python實(shí)現(xiàn)桶排序與快速排序算法結(jié)合應(yīng)用,結(jié)合實(shí)例形式分析了Python快速排序及桶排序結(jié)合應(yīng)用的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-11-11
Python實(shí)現(xiàn)冒泡排序算法的示例解析
冒泡排序(Bubble Sort)是一種簡單的排序算法。本文將詳細(xì)為大家講講Python實(shí)現(xiàn)冒泡排序算法的方法,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-06-06
Python編程中用close()方法關(guān)閉文件的教程
這篇文章主要介紹了Python編程中用close()方法關(guān)閉文件的教程,是Python編程入門中的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
使用Flask開發(fā)RESTful?API的方法實(shí)現(xiàn)
RESTful?API是一種基于REST架構(gòu)風(fēng)格設(shè)計(jì)的Web服務(wù)接口,本文主要介紹了使用Flask開發(fā)RESTful?API的方法實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11
Pycharm保存不能自動同步到遠(yuǎn)程服務(wù)器的解決方法
今天小編就為大家分享一篇Pycharm保存不能自動同步到遠(yuǎn)程服務(wù)器的解決方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06

