python中rmdir和rmtree的用法

shutil.rmtree() 是 Python 中 shutil 模块提供的一个函数,

用于递归删除整个目录树(包括子目录和所有文件)

 os.rmdir()(只能删除空目录)不同,shutil.rmtree() 可以强制删除非空目录

import shutil

# 删除指定目录及其所有内容
shutil.rmtree('path/to/directory')

### Python 中的目录操作及相关方法 Python 提供了一系列用于文件系统路径操作的标准库模块 `os` `pathlib`,这些工具使得创建、删除以及遍历目录变得简单而高效。 #### 使用 os 模块管理目录 通过导入 `os` 模块可以访问操作系统功能来执行诸如获取当前工作目录、改变默认位置等基本任务: ```python import os # 获取当前的工作目录 current_directory = os.getcwd() print(f'Current Working Directory: {current_directory}') # 改变当前工作目录到指定路径 new_path = '/home/user/documents' os.chdir(new_path) # 创建单层子目录;如果该目录已存在,则会抛出异常 FileExistsError try: os.mkdir('test_folder') except FileExistsError as e: print(e) # 创建多级子目录结构(即使父目录不存在也会被自动创建) nested_dirs = 'parent/child/grandchild' os.makedirs(nested_dirs, exist_ok=True) # 设置exist_ok参数防止重复调用时报错 # 列举给定目录下的所有条目名称列表 entries_in_dir = os.listdir('.') for entry in entries_in_dir: print(entry) # 删除空目录 os.rmdir('empty_folder') # 移除整个目录树及其内部的所有内容 import shutil shutil.rmtree('directory_to_remove', ignore_errors=False) ``` #### 使用 pathlib 库简化路径处理 从 Python 3.4 开始引入了更现代化的对象接口——`Path` 类型来自 `pathlib` 模块。这提供了更加直观的方法来进行复杂的文件系统导航查询: ```python from pathlib import Path # 构造一个新的 Path 对象表示特定文件夹的位置 base_path = Path('/tmp/my_project/data') # 测试某个路径是否存在并判断其性质 if base_path.exists(): if base_path.is_file(): print("It's a file.") elif base_path.is_dir(): print("It's a directory.") # 遍历目录中的每一个项目 for item in base_path.iterdir(): print(item.name) # 查找符合条件的第一个匹配项 matching_files = list(base_path.glob('*.csv')) first_match = next(iter(matching_files), None) if first_match: print(first_match) # 复制源文件至目标位置 source = Path('/src/dir/file.txt') destination = Path('/dst/dir/newname.txt') source.replace(destination) # 更改权限模式(仅限 Unix/Linux/MacOS) target_file = Path('/some/path/to/a/file') target_file.chmod(0o755) ``` 上述代码片段展示了如何利用内置函数轻松完成常见的目录管理维护活动[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值