问题描述
我在多个文件夹中都有.gz压缩文件,这些文件都位于名为"usa"的主文件夹中.我能够使用下面的代码提取单个文件.
I have .gz zipped files within multiple folders that are all within a main folder called "usa". I was able to extract an individual file using the code below.
import gzip
import shutil
source=r"C:\usauc300.dbf.gz"
output=r"C:\usauc300.dbf"
with gzip.open(source,"rb") as f_in, open(output,"wb") as f_out:
shutil.copyfileobj(f_in, f_out)
我搜索过高低,但是找不到等效于命令行选项 gzip -dr .....
的意思是解压缩递归",它将遍历每个文件夹并提取删除原始压缩文件时将内容移到相同位置.有谁知道我如何使用python来遍历文件夹中的文件夹,找到任何压缩文件并将其解压缩到同一位置,同时用解压缩的文件替换解压缩的文件?
I have searched high and low but can't find an equivalent to the command line option gzip -dr.....
which means "decompress recursive" and will go through each folder and extract the contents to the same location while deleting the original zipped file. Does anyone know how I can use python to loop through folders within a folder, find any zipped files and unzip them to the same location while replacing the unzipped file with the zipped one?
推荐答案
我认为这是因为gzip从不对目录进行操作,它作为一种压缩算法,与zip和tar不同,我们可以对目录进行压缩.python的gzip实现是对文件进行操作.但是,如果我们看一下os.walk调用,则目录树的递归遍历很容易.
I believe that's because gzip never operates over directories, it acts as a compression algorithm unlike zip and tar where we could compress directories. python's implementation of gzip is to operate on files. However recursive traversal of a directory tree is easy if we look at the os.walk call.
(我还没有测试过)
def gunzip(file_path,output_path):
with gzip.open(file_path,"rb") as f_in, open(output_path,"wb") as f_out:
shutil.copyfileobj(f_in, f_out)
def recurse_and_gunzip(root):
walker = os.walk(root)
for root,dirs,files in walker:
for f in files:
if fnmatch.fnmatch(f,"*.gz"):
gunzip(f,f.replace(".gz",""))
这篇关于使用python将主文件夹中的文件夹中的gz文件解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!