如何在 python 中提取 gz 文件
How to extract a gz file in python
我有一个.gz
文件,里面还有一个文件。我需要提取压缩文件中的文件。
f = gzip.open(dest, 'rb')
这只会打开文件,但我需要下载 gz
中的特定文件,而不是只打开 gz
文件。
这个问题已被标记为重复,我接受,但我还没有找到我们可以真正下载文件而不仅仅是阅读其内容的解决方案。提到的link也是如此。
您可以只打开两个文件,从 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)
否则,您可以使用 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
的文件
我有一个.gz
文件,里面还有一个文件。我需要提取压缩文件中的文件。
f = gzip.open(dest, 'rb')
这只会打开文件,但我需要下载 gz
中的特定文件,而不是只打开 gz
文件。
这个问题已被标记为重复,我接受,但我还没有找到我们可以真正下载文件而不仅仅是阅读其内容的解决方案。提到的link也是如此。
您可以只打开两个文件,从 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)
否则,您可以使用 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