python3 解压一个.gz后缀的压缩文件,如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import gzip
#解压.gz文件
def un_gz(file_name):
# 获取文件的名称,去掉后缀名
f_name = file_name.replace(".gz", "")
# 开始解压
g_file = gzip.GzipFile(file_name)
#读取解压后的文件,并写入去掉后缀名的同名文件(即得到解压后的文件)
open(f_name, "wb+").write(g_file.read())
g_file.close()
un_gz('D:\\python36\\config.gz')
可以看到在此路径下生成一个解压后的文件
注:一开始网上看到很多类似的写法但是上面第13行的写法是以下的样子
open(f_name, "w+").write(g_file.read())
实际执行会报 TypeError: write() argument must be str, not bytes,说是打开方式的问题,按照 “wb+” 的格式解决此问题
增加zip压缩格式文件解压,将脚本放到.zip文件根目录下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import zipfile
#解压.zip文件(循环解压多个文件)
def unzip_file(filePath):
for file in os.listdir(filePath):
#print(file)
path = os.path.join(filePath,file)
#开始解压
if os.path.exists(path) and '.zip' in file:
with zipfile.ZipFile(file) as zf:
zf.extractall()
currentPath = os.getcwd() #当前工作路径
unzip_file(currentPath)