Python os模块编程教程(python3 os模块)

os模块是Python标准库中最重要的模块之一,它提供了与操作系统交互的功能,允许开发者执行文件操作、目录操作、进程管理等任务。

import os

核心功能与实践

1. 文件与目录操作

# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")

# 创建目录
os.makedirs("test_dir/sub_dir", exist_ok=True)

# 列出目录内容
print("目录内容:", os.listdir())

# 重命名文件/目录
os.rename("test_dir", "renamed_dir")

# 删除目录
os.rmdir("renamed_dir/sub_dir")

2. 路径操作

# 拼接路径
file_path = os.path.join("data", "files", "document.txt")
print(f"文件路径: {file_path}")

# 检查路径是否存在
print(f"路径存在: {os.path.exists(file_path)}")

# 获取文件信息
if os.path.exists("example.txt"):
    file_stats = os.stat("example.txt")
    print(f"文件大小: {file_stats.st_size} 字节")
    print(f"最后修改时间: {file_stats.st_mtime}")

3. 进程管理

# 执行系统命令
result = os.system("echo 'Hello from OS module!'")
print(f"命令返回值: {result}")

# 获取环境变量
print(f"当前用户: {os.getenv('USER')}")
print(f"PATH环境变量: {os.getenv('PATH')}")

4. 文件操作

# 创建文件
with open("example.txt", "w") as f:
    f.write("Python os模块实践示例")

# 删除文件
if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("文件已删除")

5. 遍历目录树

# 遍历目录
print("目录树结构:")
for root, dirs, files in os.walk("."):
    print(f"当前目录: {root}")
    print(f"子目录: {dirs}")
    print(f"文件: {files}")
    print("-" * 40)

实践应用:文件搜索

def find_files(extension, search_dir="."):
    """查找指定扩展名的文件"""
    matches = []
    for root, _, files in os.walk(search_dir):
        for file in files:
            if file.endswith(extension):
                matches.append(os.path.join(root, file))
    return matches

# 查找所有.py文件
py_files = find_files(".py")
print("找到的Python文件:")
for file in py_files:
    print(f"- {file}")

高级功能

# 获取系统信息
print(f"操作系统: {os.name}")
print(f"当前进程ID: {os.getpid()}")

# 创建临时文件
import tempfile
temp_file = tempfile.NamedTemporaryFile(delete=False)
print(f"临时文件路径: {temp_file.name}")
temp_file.close()

安全提示

  • 使用os.path而不是拼接字符串来处理路径,确保跨平台兼容性
  • 对用户输入的路径进行验证,防止路径遍历攻击
  • 使用os.access()检查文件权限
# 安全示例
file_path = input("请输入文件路径: ")
if os.path.exists(file_path) and os.access(file_path, os.R_OK):
    with open(file_path) as f:
        print(f.read())
else:
    print("文件不可访问")

总结

os模块是Python系统编程的基石,提供了丰富的操作系统交互功能。掌握os模块可以让我们:

  • 高效管理文件和目录
  • 与操作系统环境交互
  • 执行系统命令
  • 编写跨平台的脚本和工具

建议在实践中多尝试os模块的各种功能,结合shutilsubprocess等模块,可以构建强大的系统工具和自动化脚本。


#编程# #学习# #python# #在头条记录我的2025#


原文链接:,转发请注明来源!