Python拥有丰富的标准库,这里介绍常用的Python模块及其简单应用示例。请注意,部分示例可能需要特定版本的Python环境,且自Python 2到Python 3存在一些不兼容的变化,以下示例假设使用的是Python 3环境。
os: 提供了与操作系统交互的各种功能。
import os
print(os.getcwd()) # 打印当前工作目录
sys: 提供对Python解释器的一些访问,用于操控Python运行时环境。
import sys
print(sys.version) # 打印Python版本信息
math: 提供数学相关的函数。
import math
print(math.sqrt(16)) # 计算16的平方根
datetime: 处理日期和时间。
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 当前日期时间格式化输出
json: JSON数据的编码和解码。
import json
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)
print(json_str) # 将字典转换为JSON字符串
requests: 简洁易用的HTTP库(非内置,需安装)。
import requests
response = requests.get('https://api.github.com')
print(response.text) # 发起GET请求并打印响应内容
re: 正则表达式操作。
import re
match = re.search(r'\d+', 'My number is 123.')
print(match.group()) # 查找并打印数字
random: 随机数生成。
import random
print(random.randint(1, 100)) # 生成1到100之间的随机整数
csv: CSV文件读写。
import csv
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', 24])
argparse: 命令行参数解析。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
print(args.foo)
shutil: 高级文件和文件夹操作。
import shutil
shutil.copyfile('source.txt', 'destination.txt') # 复制文件
glob: 文件名模式匹配。
import glob
for file in glob.glob('*.txt'):
print(file) # 打印当前目录下所有.txt文件
itertools: 迭代器函数生成工具。
import itertools
for i in itertools.count(1): # 无限计数器
print(i)
if i > 5: break # 打印前5个数字
functools: 高阶函数和操作工具。
from functools import reduce
numbers = [1, 2, 3, 4]
print(reduce(lambda x, y: x+y, numbers)) # 列表求和
urllib: URL处理和请求库。
from urllib.request import urlopen
with urlopen('https://www.example.com/') as response:
html = response.read().decode()
print(html[:250]) # 打印网页的前250个字
time: 时间访问和转换。
import time
print(time.time()) # 打印当前时间戳
os.path: 操作路径名的工具。
import os.path
print(os.path.join('mydir', 'myfile.txt')) # 合并路径
pickle: 对象序列化和反序列化。
import pickle
data = {'a': 1, 'b': 2}
with open('data.pickle', 'wb') as f:
pickle.dump(data, f)
logging: 日志记录。
import logging
logging.basicConfig(level=logging.INFO)
logging.info('This is an info message') # 记录日志信息
configparser: INI配置文件解析。
import configparser
config = configparser.ConfigParser()
config.read('settings.ini')
print(config['Section']['key']) # 读取配置文件中的值