python中常用模块及其函数的使用

Python 具有许多强大的模块和库,可以用于各种编程任务。以下是一些常用的 Python 模块及其主要函数:

1. os 模块

用于与操作系统进行交互。

import os

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

# 列出指定目录下的文件和目录
os.listdir('path')

# 创建目录
os.mkdir('directory_name')

# 删除文件
os.remove('file_name')

# 重命名文件或目录
os.rename('old_name', 'new_name')

2. sys 模块

用于访问与 Python 解释器相关的功能和参数。

import sys

# 获取命令行参数列表
sys.argv

# 退出程序
sys.exit()

# 获取 Python 解释器的版本信息
sys.version

# 修改模块搜索路径
sys.path.append('path_to_module')

3. re 模块

用于正则表达式匹配操作。

import re

# 匹配正则表达式
match = re.match(r'pattern', 'string')

# 搜索正则表达式
search = re.search(r'pattern', 'string')

# 替换匹配的子串
sub = re.sub(r'pattern', 'replacement', 'string')

# 分割字符串
split = re.split(r'pattern', 'string')

4. math 模块

提供基本的数学函数。

import math

# 计算平方根
math.sqrt(16)

# 计算阶乘
math.factorial(5)

# 计算对数
math.log(100, 10)

# 计算三角函数
math.sin(math.pi / 2)

5. datetime 模块

用于处理日期和时间。

import datetime

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

# 创建特定日期和时间
dt = datetime.datetime(2020, 1, 1, 12, 0, 0)

# 计算时间差
delta = datetime.timedelta(days=1)
new_date = now + delta

# 格式化日期和时间
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')

6. json 模块

用于解析和生成 JSON 数据。

import json

# 将 Python 对象编码为 JSON 字符串
json_str = json.dumps({'key': 'value'})

# 将 JSON 字符串解码为 Python 对象
data = json.loads(json_str)

# 将 Python 对象写入 JSON 文件
with open('data.json', 'w') as f:
    json.dump(data, f)

# 从 JSON 文件读取 Python 对象
with open('data.json', 'r') as f:
    data = json.load(f)

7. requests 模块

用于发送 HTTP 请求(需要安装第三方库 requests)。

import requests

# 发送 GET 请求
response = requests.get('https://api.example.com/data')

# 发送 POST 请求
response = requests.post('https://api.example.com/data', data={'key': 'value'})

# 获取响应状态码
status_code = response.status_code

# 获取响应内容
content = response.text

# 解析 JSON 响应
data = response.json()

8. pandas 模块

用于数据操作和分析(需要安装第三方库 pandas)。

import pandas as pd

# 创建 DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# 读取 CSV 文件
df = pd.read_csv('data.csv')

# 数据筛选
filtered_df = df[df['A'] > 1]

# 数据汇总
summary = df.describe()

当然,以下是另外 12 个常用的 Python 模块及其主要函数:

9. collections 模块

提供了许多有用的集合类。

import collections

# 计数器
counter = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])

# 有序字典
ordered_dict = collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# 默认字典
default_dict = collections.defaultdict(int)
default_dict['a'] += 1

# 命名元组
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(10, 20)

10. itertools 模块

提供了用于高效循环的函数。

import itertools

# 生成笛卡尔积
product = itertools.product([1, 2], ['a', 'b'])

# 生成排列
permutations = itertools.permutations([1, 2, 3])

# 生成组合
combinations = itertools.combinations([1, 2, 3], 2)

# 无限迭代
counter = itertools.count(start=10, step=2)

11. functools 模块

提供了高阶函数,用于操作或返回其他函数。

import functools

# 创建偏函数
def add(a, b):
    return a + b

add_five = functools.partial(add, 5)
result = add_five(10)  # 结果是15

# 缓存函数结果
@functools.lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

12. random 模块

用于生成随机数。

import random

# 生成随机浮点数
rand_float = random.random()

# 生成指定范围内的随机整数
rand_int = random.randint(1, 10)

# 从列表中随机选择
choice = random.choice(['a', 'b', 'c'])

# 打乱列表
random.shuffle([1, 2, 3, 4, 5])

13. time 模块

提供与时间相关的函数。

import time

# 获取当前时间戳
current_time = time.time()

# 暂停程序执行
time.sleep(2)

# 格式化时间
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

14. logging 模块

用于记录日志信息。

import logging

# 配置日志记录
logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w')

# 记录不同级别的日志
logging.debug('Debug message')
logging.info('Info message')
logging.warning('Warning message')
logging.error('Error message')
logging.critical('Critical message')

15. subprocess 模块

用于生成新的进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。

import subprocess

# 执行命令并获取输出
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
output = result.stdout

16. sqlite3 模块

用于与 SQLite 数据库进行交互。

import sqlite3

# 连接到数据库
conn = sqlite3.connect('example.db')

# 创建游标
cursor = conn.cursor()

# 执行 SQL 查询
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')

# 插入数据
cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))

# 提交事务
conn.commit()

# 查询数据
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()

# 关闭连接
conn.close()

17. threading 模块

用于创建和管理线程。

import threading

# 定义线程函数
def print_numbers():
    for i in range(5):
        print(i)

# 创建并启动线程
thread = threading.Thread(target=print_numbers)
thread.start()

# 等待线程结束
thread.join()

18. multiprocessing 模块

用于并行执行任务。

import multiprocessing

# 定义进程函数
def print_numbers():
    for i in range(5):
        print(i)

# 创建并启动进程
process = multiprocessing.Process(target=print_numbers)
process.start()

# 等待进程结束
process.join()

19. socket 模块

用于网络通信。

import socket

# 创建 TCP/IP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接到服务器
sock.connect(('localhost', 8080))

# 发送数据
sock.sendall(b'Hello, world')

# 接收数据
data = sock.recv(1024)

# 关闭连接
sock.close()

20. base64 模块

用于 Base64 编码和解码。

import base64

# 编码
encoded = base64.b64encode(b'hello world')

# 解码
decoded = base64.b64decode(encoded)

21. hashlib 模块

用于生成哈希值。

import hashlib

# 创建哈希对象
hash_obj = hashlib.sha256()

# 更新哈希对象
hash_obj.update(b'hello world')

# 获取十六进制哈希值
hash_value = hash_obj.hexdigest()

22. uuid 模块

用于生成唯一标识符(UUID)。

import uuid

# 生成 UUID4
unique_id = uuid.uuid4()

23. shutil 模块

用于高级的文件操作。

import shutil

# 复制文件
shutil.copy('source.txt', 'destination.txt')

# 移动文件
shutil.move('source.txt', 'destination.txt')

# 删除文件
shutil.rmtree('directory_name')

这些模块和函数只是 Python 中的一小部分,Python 的丰富生态系统还包括许多其他功能强大的库和模块,可以根据具体需求进行选择。

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值