Python 标准库是一组内置的模块和包,提供了各种功能,从文件操作到网络编程、正则表达式、数据库访问等等。以下是一些 Python 标准库中常用模块的概览:

1. os 模块:

提供与操作系统交互的功能,包括文件和目录操作、路径处理等。
import os

# 获取当前工作目录
current_directory = os.getcwd()

# 列出目录中的文件和子目录
files_and_directories = os.listdir("/path/to/directory")

2. sys 模块:

提供与 Python 解释器交互的功能,包括命令行参数、标准输入输出等。
import sys

# 命令行参数
print(sys.argv)

# 标准错误输出
sys.stderr.write("This is an error message\n")

3. datetime 模块:

提供日期和时间的处理功能。
from datetime import datetime

# 获取当前日期和时间
current_time = datetime.now()

# 格式化日期和时间
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")

4. random 模块:

用于生成伪随机数。
import random

# 生成随机整数
random_number = random.randint(1, 10)

5. math 模块:

提供数学运算相关的功能。
import math

# 计算平方根
square_root = math.sqrt(25)

6. re 模块:

用于正则表达式操作。
import re

# 匹配字符串
pattern = re.compile(r'\b\w+\b')
matches = pattern.findall("This is a sample text.")

7. json 模块:

用于处理 JSON 数据。
import json

# 将 Python 对象转换为 JSON 字符串
json_string = json.dumps({"name": "John", "age": 25})

# 将 JSON 字符串转换为 Python 对象
python_object = json.loads(json_string)

8. urllib 模块:

用于处理 URL 相关的操作。
from urllib import request

# 发送 HTTP 请求
response = request.urlopen("https://www.example.com")
content = response.read().decode("utf-8")

9. sqlite3 模块:

用于访问 SQLite 数据库。
import sqlite3

# 连接数据库
connection = sqlite3.connect("mydatabase.db")

# 创建游标对象
cursor = connection.cursor()

# 执行 SQL 查询
cursor.execute("SELECT * FROM mytable")

# 获取查询结果
results = cursor.fetchall()

# 关闭连接
connection.close()

以上是一些 Python 标准库中常用模块的概览。标准库中还包含很多其他有用的模块,根据具体需求选择合适的模块进行使用。


转载请注明出处:http://www.zyzy.cn/article/detail/13279/Python3