Python 的 os
模块是 Python 标准库的一部分,因此不需要单独安装。它提供了许多与操作系统交互的功能,如文件和目录操作、环境变量访问等。
os
模块允许 Python 程序与底层操作系统进行交互。它包含了许多函数,可以用来获取文件属性、修改文件权限、创建和删除目录、执行系统命令等。
os
模块可以在不同的操作系统上运行,提供了统一的接口来处理文件系统和操作系统相关的任务。以下是一些使用 os
模块的常见操作示例:
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"Current working directory: {current_dir}")
# 创建一个新目录
new_dir = "new_folder"
if not os.path.exists(new_dir):
os.makedirs(new_dir)
print(f"Directory '{new_dir}' created.")
# 列出目录中的所有文件和子目录
files_in_dir = os.listdir(current_dir)
print(f"Files and directories in current directory: {files_in_dir}")
# 删除一个文件
file_to_delete = "example.txt"
if os.path.isfile(file_to_delete):
os.remove(file_to_delete)
print(f"File '{file_to_delete}' deleted.")
# 获取环境变量
home_dir = os.getenv("HOME")
print(f"Home directory: {home_dir}")
PermissionError
。FileNotFoundError
。os.path.exists()
检查路径是否存在。os.name
或 platform.system()
来检测当前操作系统,并根据不同的操作系统执行不同的代码逻辑。通过这些方法和示例,你应该能够有效地使用 os
模块来处理与操作系统相关的任务。
领取专属 10元无门槛券
手把手带您无忧上云