Python 提供了丰富的标准库和第三方模块,用于处理各种任务。以下是一些常用的 Python 模块及其常见使用方法:
1. os
模块
os模块提供了与操作系统交互的功能,如文件操作、目录操作、环境变量等。
常见用法:
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")
# 列出指定目录中的文件和目录
files = os.listdir('.')
print(f"当前目录中的文件和目录: {files}")
# 创建新目录
os.mkdir('new_folder')
# 删除文件或目录
os.remove('file.txt') # 删除文件
os.rmdir('new_folder') # 删除目录
# 检查路径是否存在
exists = os.path.exists('some_file.txt')
print(f"文件是否存在: {exists}")
2. sys
模块
sys
模块提供了与 Python 解释器交互的功能,如访问命令行参数、退出程序等。
常见用法:
import sys
# 获取命令行参数
args = sys.argv
print(f"命令行参数: {args}")
# 退出程序
sys.exit(0) # 0 表示正常退出
# 获取Python解释器的版本信息
version = sys.version
print(f"Python 版本: {version}")
3. datetime
模块
datetime
模块提供了处理日期和时间的功能。
常见用法:
from datetime import datetime, timedelta
# 获取当前日期和时间
now = datetime.now()
print(f"当前时间: {now}")
# 格式化日期和时间
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"格式化时间: {formatted_time}")
# 日期加减
yesterday = now - timedelta(days=1)
print(f"昨天的时间: {yesterday}")
4. json
模块
json
模块用于解析和生成 JSON 数据。
常见用法:
import json
# Python对象转为JSON字符串
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(f"JSON 字符串: {json_str}")
# JSON字符串转为Python对象
data = json.loads(json_str)
print(f"Python 对象: {data}")
# 将JSON数据写入文件
with open('data.json', 'w') as f:
json.dump(data, f)
# 从文件读取JSON数据
with open('data.json', 'r') as f:
data_from_file = json.load(f)
print(f"从文件读取的JSON数据: {data_from_file}")
5. random
模块
random
模块提供了生成随机数、随机选择等功能。
常见用法:
import random
# 生成0到1之间的随机浮点数
rand_float = random.random()
print(f"随机浮点数: {rand_float}")
# 生成指定范围内的随机整数
rand_int = random.randint(1, 100)
print(f"随机整数: {rand_int}")
# 随机选择
choices = ['apple', 'banana', 'cherry']
choice = random.choice(choices)
print(f"随机选择: {choice}")
# 打乱顺序
random.shuffle(choices)
print(f"打乱顺序后的列表: {choices}")