我有一个.gz
文件,里面有另一个文件。我需要在压缩文件中提取文件。
f = gzip.open(dest, 'rb')
这只打开文件,但我需要下载gz
内的特定文件,而不是只打开gz
文件。
这个问题已被标记为重复,我接受,但我还没有找到一个解决方案,我们可以实际下载该文件而不只是阅读其内容。提到的链接也是如此。
您可以打开两个文件,从gzipped
文件中读取并写入另一个文件(以块为单位以避免堵塞内存)。
import gzip
def gunzip(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
while True:
block = s_file.read(block_size)
if not block:
break
else:
d_file.write(block)
d_file.write(block)
否则,您可以使用shutil
中建议的How to unzip gz file using Python:
import gzip
import shutil
def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
shutil.copyfileobj(s_file, d_file, block_size)
这两种解决方案都适用于Python 2和3。
性能方面,至少在我的系统上它们基本相同:
%timeit gunzip(source_filepath, dest_filepath)
# 129 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit gunzip_shutil(source_filepath, dest_filepath)
# 132 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
我已经解决了这个问题:
f = gzip.open(dest, 'r')
file_content = f.read()
file_content = file_content.decode('utf-8')
f_out = open('file', 'w+')
f_out.write(file_content)
f.close()
f_out.close()
dest是gz
的文件