如何用python解压 .gz文件
时间: 2023-11-21 18:56:24 浏览: 40
以下是用Python解压.gz文件的方法:
```python
import gzip
import shutil
def un_gzfile(gz_path, dst_path):
with gzip.open(gz_path, 'rb') as f_in:
with open(dst_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
print("文件解压成功!")
```
使用方法:
```python
un_gzfile('example.gz', 'example.txt')
```
其中,`gz_path`为.gz文件的路径,`dst_path`为解压后文件的路径。
相关问题
如何用python解压 .tar.gz文件
以下是使用Python解压.tar.gz文件的方法:
```python
import tarfile
# 打开.tar.gz文件
filename = "example.tar.gz"
tar = tarfile.open(filename, "r:gz")
# 解压缩文件到指定目录
target_path = "/path/to/target/directory"
tar.extractall(path=target_path)
# 关闭文件
tar.close()
```
其中,`tarfile.open()`函数用于打开.tar.gz文件,第一个参数为文件名,第二个参数为打开模式,"r:gz"表示以gzip压缩格式读取文件。`tar.extractall()`函数用于解压缩文件到指定目录,其中`path`参数为目标目录的路径。最后,使用`tar.close()`函数关闭文件。
python解压.tar.gz文件
Python可以使用tarfile模块来解压.tar.gz文件。下面是一个简单的示例代码:
```
import tarfile
# 打开.tar.gz文件
tar = tarfile.open("example.tar.gz", "r:gz")
# 解压到指定目录
tar.extractall(path="path/to/extract")
# 关闭文件
tar.close()
```
在这个示例中,我们首先使用`tarfile.open()`函数打开.tar.gz文件。然后,我们使用`tar.extractall()`函数将文件解压到指定的目录中。最后,我们使用`tar.close()`函数关闭文件。
需要注意的是,`tarfile.open()`函数的第二个参数应该是"r:gz",表示以gzip格式读取文件。如果文件是以其他格式压缩的,需要相应地更改参数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)