python遍历目录压缩文件夹
时间: 2023-08-08 20:11:14 浏览: 159
python遍历文件夹
4星 · 用户满意度95%
可以使用以下Python代码来遍历目录并压缩文件夹:
```python
import os
from shutil import make_archive
def compress_folders(path):
path_list = os.listdir(path) # 获取目录列表
for folder in path_list:
folder_path = os.path.join(path, folder) # 定义需要压缩的文件夹路径
if os.path.isdir(folder_path): # 判断是否为文件夹
zip_name = os.path.join(path, folder) # 定义压缩后的目标文件名
make_archive(zip_name, 'zip', folder_path) # 压缩文件夹
# 调用函数并传入目录路径
compress_folders('D:\\BaiduNetdiskDownload')
```
这段代码会遍历指定目录下的所有文件夹,并将每个文件夹压缩成一个zip文件。你可以将`'D:\\BaiduNetdiskDownload'`替换为你想要遍历的目录路径。
#### 引用[.reference_title]
- *1* [python文件夹遍历压缩](https://blog.csdn.net/weixin_43707795/article/details/122263868)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [python遍历文件夹解压](https://blog.csdn.net/Rone_kiin/article/details/127511830)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Python遍历文件夹中的压缩文件自动解压缩到其目录下](https://blog.csdn.net/LiuKuoHai/article/details/118657198)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文