2025-03-04
编程
00
请注意,本文编写于 55 天前,最后修改于 54 天前,其中某些信息可能已经过时。

目录

基本导入
常用功能
1. 文件和目录操作

Python 的 os 模块提供了与操作系统交互的功能。它允许我们执行许多常见的系统任务,如文件和目录管理、环境变量访问以及进程管理等。

基本导入

首先,需要在脚本中导入 os 模块:

python
import os

常用功能

1. 文件和目录操作

  • 获取当前工作目录

    python
    current_directory = os.getcwd() print(f"Current working directory: {current_directory}")
  • 改变当前工作目录

    python
    os.chdir('/path/to/directory')
  • 列出目录内容

    python
    files_and_directories = os.listdir('.') print("Files and directories in '.' :") for item in files_and_directories: print(item)
  • 创建新目录

    python
    os.mkdir('new_directory') # 创建多级目录 os.makedirs('parent_directory/child_directory')
  • 删除目录

    python
    os.rmdir('new_directory') # 只能删除空目录 os.removedirs('parent_directory/child_directory') # 删除多级目录
  • 重命名文件或目录

    python
    os.rename('old_name', 'new_name')
  • 检查路径是否为文件或目录

    python
    print(os.path.isfile('example.txt')) print(os.path.isdir('example_directory'))

2. 环境变量

  • 获取环境变量

    python
    home_directory = os.getenv('HOME') print(f"Home directory: {home_directory}")
  • 设置环境变量(注意:这只在当前进程中有效):

    python
    os.environ['MY_VARIABLE'] = 'my_value'

3. 进程管理

  • 运行外部命令

    python
    os.system('echo Hello, World!')

    更推荐使用 subprocess 模块来处理更复杂的子进程调用。

  • 获取进程 ID (PID)

    python
    pid = os.getpid() print(f"Current process ID: {pid}")
  • 获取父进程 ID (PPID)

    python
    ppid = os.getppid() print(f"Parent process ID: {ppid}")

4. 路径操作

  • 拼接路径

    python
    path = os.path.join('parent_directory', 'child_directory', 'file.txt') print(path)
  • 拆分路径

    python
    directory, filename = os.path.split('/path/to/file.txt') print(directory, filename)
  • 获取文件扩展名

    python
    extension = os.path.splitext('file.txt')[1] print(extension)

5. 错误处理

当你执行文件或目录操作时,可能会遇到各种异常情况。使用 try-except 结构可以帮助你优雅地处理这些异常:

python
try: os.remove('non_existent_file.txt') except FileNotFoundError: print("File not found.") except PermissionError: print("Permission denied.") except Exception as e: print(f"An error occurred: {e}")