我电脑有一百个文件压缩包,每个压缩包名称都不同,该如何批量解压呢,用Python实现
时间: 2024-04-30 15:23:48 浏览: 21
可以使用Python的zipfile库来实现批量解压缩。具体步骤如下:
1. 导入zipfile库
```python
import zipfile
```
2. 定义解压函数
```python
def unzip(file_path, dest_path):
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(dest_path)
```
其中,file_path是需要解压的文件路径,dest_path是解压后文件的存储路径。
3. 遍历所有压缩包文件
```python
import os
# 定义压缩包所在目录
zip_dir = 'path/to/zip/files'
# 遍历所有文件
for file_name in os.listdir(zip_dir):
# 判断是否为压缩包文件
if file_name.endswith('.zip'):
# 构造文件路径
file_path = os.path.join(zip_dir, file_name)
# 解压文件
unzip(file_path, zip_dir)
```
在遍历所有文件时,通过判断文件名的后缀是否为.zip来筛选出压缩包文件,然后调用解压函数进行解压。
完整代码如下:
```python
import os
import zipfile
# 定义解压函数
def unzip(file_path, dest_path):
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(dest_path)
# 定义压缩包所在目录
zip_dir = 'path/to/zip/files'
# 遍历所有文件
for file_name in os.listdir(zip_dir):
# 判断是否为压缩包文件
if file_name.endswith('.zip'):
# 构造文件路径
file_path = os.path.join(zip_dir, file_name)
# 解压文件
unzip(file_path, zip_dir)
```
将代码中的'path/to/zip/files'替换为实际的压缩包所在目录即可。
相关推荐
![bat](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)