ZetCode

Python OS 模块

最后修改:2025 年 2 月 15 日

在本文中,我们将展示如何在 Python 中使用 os 模块。os 模块提供了一种与操作系统交互的方式,允许您执行诸如文件和目录操作、环境变量管理和进程管理等任务。

os 模块对于诸如导航文件系统、创建和删除文件以及使用环境变量等任务特别有用。

导航文件系统

以下示例演示了如何使用 os 模块导航文件系统。

main.py
import os

# Get the current working directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)

# Change the current working directory
os.chdir('/tmp')
print("Changed Directory:", os.getcwd())

# List files and directories in the current directory
print("Files and Directories:", os.listdir())

在此程序中,os.getcwd 函数用于获取当前工作目录,os.chdir 用于更改目录,os.listdir 用于列出文件和目录。

使用文件和目录

以下示例演示了如何使用 os 模块创建、重命名和删除文件和目录。

main.py
import os

# Create a new directory
os.mkdir('new_directory')
print("Directory Created:", 'new_directory')

# Rename the directory
os.rename('new_directory', 'renamed_directory')
print("Directory Renamed:", 'renamed_directory')

# Create a new file
with open('new_file.txt', 'w') as f:
    f.write('Hello, World!')
print("File Created:", 'new_file.txt')

# Delete the file
os.remove('new_file.txt')
print("File Deleted:", 'new_file.txt')

# Delete the directory
os.rmdir('renamed_directory')
print("Directory Deleted:", 'renamed_directory')

在此程序中,os.mkdir 函数用于创建目录,os.rename 用于重命名目录,os.remove 用于删除文件,os.rmdir 用于删除目录。

$ python main.py
Directory Created: new_directory
Directory Renamed: renamed_directory
File Created: new_file.txt
File Deleted: new_file.txt
Directory Deleted: renamed_directory

环境变量

以下示例演示了如何使用 os 模块处理环境变量。

main.py
import os

# Get the value of an environment variable
home_directory = os.getenv('HOME')
print("Home Directory:", home_directory)

# Set a new environment variable
os.environ['MY_VAR'] = 'my_value'
print("MY_VAR:", os.getenv('MY_VAR'))

# List all environment variables
print("Environment Variables:", os.environ)

在此程序中,os.getenv 函数用于检索环境变量的值,os.environ 用于设置新的环境变量,os.environ 也用于列出所有环境变量。

运行系统命令

以下示例演示了如何使用 os 模块运行系统命令。

main.py
import os

# Run a system command
os.system('ls -l')

在此程序中,os.system 函数用于执行 ls -l 命令,该命令列出当前目录中的文件和目录。

使用 os.path 进行路径操作

以下示例演示了如何使用 os.path 子模块操作文件路径。

main.py
import os

# Join path components
path = os.path.join('/home', 'user', 'documents', 'file.txt')
print("Joined Path:", path)

# Get the basename of the path
basename = os.path.basename(path)
print("Basename:", basename)

# Get the directory name of the path
dirname = os.path.dirname(path)
print("Dirname:", dirname)

# Check if the path exists
exists = os.path.exists(path)
print("Path Exists:", exists)

在此程序中,os.path.join 函数用于连接路径组件,os.path.basename 用于获取路径的基本名称,os.path.dirname 用于获取目录名称,os.path.exists 用于检查路径是否存在。

使用 os.rename 重命名文件

以下示例演示了如何使用 os.rename 函数重命名文件,并使用 os.path.exists 检查文件是否存在。

main.py
import os

# Specify the file name
file_name = 'myfile.txt'

# Check if the file exists
if os.path.exists(file_name):
    # Rename the file
    os.rename('myfile.txt', 'myfile2.txt')
    print("File renamed successfully.")
else:
    print('Failed to rename file: File does not exist.')

在此程序中,os.path.exists 函数用于检查文件是否存在,os.rename 用于在文件存在时重命名文件。如果文件不存在,则显示相应的消息。

$ python main.py
File renamed successfully.

如果文件不存在,程序将输出

$ python main.py
Failed to rename file: File does not exist.

使用 os.listdir 列出目录

以下示例演示了如何使用 os.listdir 函数列出目录的内容。

main.py
import os

# List all entries in the current directory
content = os.listdir('.')
print("Directory Contents:", content)

在此程序中,os.listdir 函数用于列出当前目录中的所有条目。列表包括文件和目录,但不包括特殊条目,如 '.''..'

使用 os.scandir 列出目录

以下示例演示了如何使用 os.scandir 函数列出目录的内容,该函数提供有关文件属性等额外信息。

main.py
import os
from datetime import datetime

# Specify the directory path
path = '.'

# Use scandir to list entries with additional info
with os.scandir(path) as it:
    for entry in it:
        print(f'{entry.name} - Created: {datetime.fromtimestamp(entry.stat().st_ctime)}')

在此程序中,os.scandir 函数用于列出当前目录中的条目及其创建时间。entry.stat 方法提供文件元数据,如创建时间 (st_ctime)。

使用 os.walk 遍历目录

以下示例演示了如何使用 os.walk 函数递归遍历目录。此函数通过从上到下或从下到上遍历目录树来生成目录树中的文件名和目录名。

main.py
import os

# Traverse the directory tree starting from the current directory
for root, dirs, files in os.walk(os.path.abspath(".")):
    # Print all files in the current directory
    for name in files:
        print(os.path.join(root, name))
    # Print all subdirectories in the current directory
    for name in dirs:
        print(os.path.join(root, name))

在此程序中,os.walk 函数用于遍历从当前目录开始的目录树。对于每个目录,它会列出所有文件和子目录,并使用 os.path.join 打印它们的完整路径。

os.walk 函数对于递归处理目录树中的文件和目录特别有用。

来源

Python OS 模块 - 文档

在本文中,我们展示了如何使用 os 模块在 Python 中与操作系统进行交互。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程