python 解压文件
时间: 2023-06-11 16:07:32 浏览: 61
你可以使用Python的标准库`zipfile`来解压zip文件,例如:
```python
import zipfile
# 打开zip文件
with zipfile.ZipFile('example.zip', 'r') as zip_ref:
# 解压文件到指定目录
zip_ref.extractall('destination_folder')
```
如果要解压其他类型的文件,例如.tar.gz或.rar,可以使用对应的库进行解压,例如`tarfile`和`rarfile`。
相关问题
python 压缩 文件
以下是Python压缩文件的两个例子:
1. 压缩单个文件
```python
from zipfile import ZipFile
with ZipFile('output.zip', 'w') as z:
z.write('input.txt')
```
2. 压缩多个文件
```python
from zipfile import ZipFile
with ZipFile('output.zip', 'w') as z:
z.write('file1.txt')
z.write('file2.txt')
z.write('file3.txt')
```
以上两个例子都使用了Python标准库中的zipfile模块。第一个例子中,我们使用了ZipFile类来创建一个名为output.zip的压缩文件,并将input.txt文件写入其中。第二个例子中,我们在ZipFile类中多次调用write方法,将多个文件写入压缩文件中。
python解压文件
要解压文件,你可以使用 Python 的 zipfile 模块。下面是一个简单的示例代码:
```python
import zipfile
def unzip_file(file_path, extract_path):
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
# 指定要解压的文件路径和解压后的目标路径
file_path = 'path/to/your/file.zip'
extract_path = 'path/to/your/destination/folder'
# 调用函数解压文件
unzip_file(file_path, extract_path)
```
你只需要将 `file_path` 替换为你要解压的文件路径,`extract_path` 替换为你想要将文件解压到的目标文件夹路径。运行代码后,压缩文件将被解压到指定的目标文件夹中。