在 Python 中,os 模块提供了与操作系统交互的功能,包括文件和目录操作、路径处理、进程控制等。以下是一些 os 模块的基本用法:

获取当前工作目录:
import os

current_directory = os.getcwd()
print(current_directory)

切换工作目录:
os.chdir("/path/to/new/directory")

列出目录中的文件和子目录:
files_and_directories = os.listdir("/path/to/directory")
print(files_and_directories)

创建目录:
os.mkdir("/path/to/new/directory")

创建多级目录:
os.makedirs("/path/to/new/directory/subdirectory")

删除文件:
os.remove("/path/to/file")

删除目录:
os.rmdir("/path/to/empty/directory")

删除目录及其内容:
import shutil

shutil.rmtree("/path/to/non-empty/directory")

文件路径拼接:
path = os.path.join("/path/to", "file.txt")
print(path)

获取文件名和目录名:
path = "/path/to/file.txt"
filename = os.path.basename(path)
directory = os.path.dirname(path)
print("Filename:", filename)
print("Directory:", directory)

检查文件或目录是否存在:
exists = os.path.exists("/path/to/file_or_directory")
print(exists)

检查是否是文件:
is_file = os.path.isfile("/path/to/file")
print(is_file)

检查是否是目录:
is_directory = os.path.isdir("/path/to/directory")
print(is_directory)

执行命令:
os.system("command")

这些是一些 os 模块中常用的功能。在实际应用中,这些功能通常用于文件和目录的管理,以及与操作系统交互的一些任务。


转载请注明出处:http://www.zyzy.cn/article/detail/13275/Python3