import os
# 获取当前工作目录
current_directory = os.getcwd()
print(f"当前工作目录是: {current_directory}")
# 列出指定目录下的所有文件和文件夹
directory_contents = os.listdir(current_directory)
print(f"当前目录下的内容有: {directory_contents}")
# 创建一个新的文件夹
new_folder = "new_folder"
os.makedirs(new_folder, exist_ok=True)
print(f"创建了新的文件夹: {new_folder}")
# 删除一个空文件夹
os.rmdir(new_folder)
print(f"删除了文件夹: {new_folder}")
# 检查路径是否存在
path_to_check = "example.txt"
if os.path.exists(path_to_check):
print(f"{path_to_check} 存在")
else:
print(f"{path_to_check} 不存在")
# 获取文件的绝对路径
absolute_path = os.path.abspath(path_to_check)
print(f"{path_to_check} 的绝对路径是: {absolute_path}")
# 分离文件名和扩展名
filename, file_extension = os.path.splitext("example.txt")
print(f"文件名是: {filename}, 扩展名是: {file_extension}")
# 更改当前工作目录
try:
os.chdir("..")
print("成功更改了当前工作目录")
except FileNotFoundError:
print("无法更改当前工作目录,目标目录不存在")
os.getcwd() 返回当前工作目录的路径。os.listdir() 列出指定目录下的所有文件和文件夹。os.makedirs() 可以创建多级目录,exist_ok=True 参数确保如果目录已存在不会抛出异常。os.rmdir() 删除一个空文件夹。os.path.exists() 检查指定路径是否存在。os.path.abspath() 返回文件或目录的绝对路径。os.path.splitext() 将文件名和扩展名分开。os.chdir() 更改当前工作目录,使用 try-except 块处理可能的错误。希望这些示例代码和解释对你理解 os 模块有所帮助。
上一篇:python 字典排序
下一篇:python web开发
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站