当前位置: 代码网 > it编程>前端脚本>Python > Python 24个常用模块编程必备知识库

Python 24个常用模块编程必备知识库

2026年03月12日 Python 我要评论
1.os - 系统交互大师import os # 查看当前工作目录 print(os.getcwd()) # 创建新目录 os.mkdir('new_fold

1.os - 系统交互大师

import os               # 查看当前工作目录  
print(os.getcwd())      # 创建新目录  
os.mkdir('new_folder')  # 列出指定目录下的文件和子目录  
for item in os.listdir('.'):  
print(item)  
  • os模块是python与操作系统对话的桥梁,让你轻松进行文件和目录操作,如获取当前工作目录、创建新目录、列出目录内容等。

2.sys - 程序运行内幕探索者

import sys           # 输出python版本信息  
print(sys.version)   # 打印命令行参数  
for arg in sys.argv:  
print(arg)  
  • sys模块提供了访问和控制python解释器运行时环境的方法,比如查看python版本、获取命令行参数等,帮你洞察程序内部运作机制。

3.datetime - 时间管理专家

from datetime 
import datetime, timedelta  
# 获取当前日期时间  
now = datetime.now()  
print(now)  
# 计算未来日期  
future_date = now + timedelta(days=30)  
print(future_date)  
  • datetime模块让处理日期和时间变得简单直观,你可以获取当前时间、计算时间间隔、进行日期格式化等,是编写与时间相关的程序不可或缺的好帮手。

4.math - 数学运算宝库

import math    
# 计算圆面积  
radius = 5  
area = math.pi * radius ##  2  
print(area)    
# 计算最大公约数  
num1, num2 = ¾, 21  
gcd = math.gcd(num1, num2)  
print(gcd)  
  • math模块封装了大量数学函数和常量,如求平方根、计算圆周率、求最大公约数等,满足你的数学运算需求。

5.random - 随机数生成魔术师

import random    
# 生成一个[0, 1)之间的随机浮点数  
rand_float = random.random()  
print(rand_float)    
# 随机从列表中选取一个元素  
choices = ['apple', 'banana', 'orange']  
random_choice = random.choice(choices)  
print(random_choice)  
  • random模块负责生成各种类型的随机数,以及对列表等容器进行随机抽样,为你的程序添加不确定性,模拟真实世界的随机行为。

6.csv - 数据导出导入能手

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(逗号分隔值)文件的读写操作,无论是保存数据还是分析外部数据源,它都是你的得力助手。

7.json - json数据处理好帮手

import json    
# 将python对象转换为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数据,使得python程序能够轻松与使用json格式的web服务或其他应用程序交换数据。

8.requests - 网络请求小飞侠

import requests    
# 发送get请求并打印响应内容  
response = requests.get('https://api.github.com')  
print(response.text)  
  • requests库简化了http请求的发送过程,无论是get、post还是其他方法,只需几行代码就能实现,大大提升了网络通信效率。

9.pandas - 数据分析与处理巨擘

import pandas as pd    
# 从csv文件加载数据到dataframe  
df = pd.read_csv('data.csv')    
# 查看前5行数据  
print(df.head())  
  • pandas库提供了强大的数据结构dataframe,用于高效地进行数据分析、清洗、统计和可视化,是python数据科学领域的核心工具之一。

10.numpy - 科学计算与数组操作神器

import numpy as np    
# 创建一个2x2的数组  
arr = np.array([[1, 2], [3, 4]])  
print(arr)    
# 计算数组元素之和  
sum_arr = np.sum(arr)  
print(sum_arr)  
  • numpy库提供高性能的多维数组对象和丰富的数学函数,是进行数值计算、机器学习、信号处理等领域开发的基础库。

11.matplotlib - 数据可视化魔法师

import matplotlib.pyplot as plt    
# 绘制简单的折线图  
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])  
plt.show()  
  • matplotlib库用于创建静态、动态、交互式的图表,如折线图、散点图、柱状图等,是python数据可视化的首选工具。

12.scipy - 科学计算全方位助手

from scipy.optimize 
import minimize    
# 定义目标函数  
def f(x):  
return x## 2 + 10*np.sin(x)    
# 使用优化算法找到最小值  
result = minimize(f, x0=0)  
print(result.x)  
  • scipy库包含众多科学计算工具箱,如最优化、插值、积分、信号处理、统计分析等,极大地扩展了python在科学计算领域的能力。

13.re - 正则表达式猎手

import re    
# 使用正则表达式匹配邮箱地址  
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模块实现了正则表达式的支持,让你能够灵活、高效地进行文本模式匹配、查找、替换等操作。

14.threading - 多线程任务执行者

import threading    
# 定义线程任务  
def thread_task(name):  
    print(f"thread {name} started.")  
    # ... 执行任务 ...  
    print(f"thread {name} finished.")    
# 创建并启动两个线程  
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模块支持多线程编程,使程序能够在同一时刻执行多个任务,提高程序并发性能和响应速度。

15.timeit - 代码性能测量仪

import timeit    
# 测试代码块执行时间  
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模块提供了一种简便的方法来测量小段代码的执行时间,帮助开发者评估代码性能,进行优化。

16.unittest - 单元测试守护神

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标准库中的单元测试框架,通过编写测试用例来确保代码的正确性和稳定性。

17.argparse - 命令行参数解析器

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模块用于创建用户友好的命令行接口,轻松处理程序接受的命令行参数。

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模块提供了通用的日志记录系统,方便程序在运行过程中记录调试信息、异常情况等,便于问题排查和跟踪。

19.sqlite3 - 轻量级数据库连接器

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内置的sqlite数据库驱动,允许程序直接操作sqlite数据库,进行数据存储、查询等操作。

20.hashlib - 哈希函数计算者

import hashlib    
message = "hello, world!".encode()  
digest = hashlib.sha256(message).hexdigest()  
print(digest)  
  • hashlib模块提供了多种安全的哈希函数,如sha-256,用于生成消息摘要或校验数据完整性。

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,包括解析、构建、搜索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模块提供了高级文件和目录操作功能,如复制、移动文件,删除目录及其内容等。

23.itertools - 生成器与迭代器魔法工厂

import itertools    
combinations = itertools.combinations(range(4), 2)  
for combo in combinations:  
print(combo)  
  • itertools模块包含了一系列高效且内存友好的迭代器函数,如生成组合、排列、无限序列等,极大丰富了python的循环结构。

24.functools - 高级函数工具箱

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模块提供了许多用于处理函数的工具,如装饰器、高阶函数等,有助于编写更简洁、更高效的代码。

总结

到此这篇关于python 24个常用模块编程必备知识库的文章就介绍到这了,更多相关python常用模块内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com