Python 3.x 如何在shutil.register\u archive\u格式中注册.gz格式在shutil.unpack\u archive中使用相同的格式
我有Example.json.gz,我想使用shutil.unpack_archive()在python中解压或提取它 但是,由于.gz格式不在默认格式列表中,因此它会给出错误“shutil.ReadError:Unknown archive format”Python 3.x 如何在shutil.register\u archive\u格式中注册.gz格式在shutil.unpack\u archive中使用相同的格式,python-3.x,Python 3.x,我有Example.json.gz,我想使用shutil.unpack_archive()在python中解压或提取它 但是,由于.gz格式不在默认格式列表中,因此它会给出错误“shutil.ReadError:Unknown archive format” 因此,必须首先使用shutil.register\u archive\u格式进行注册。有人能帮我注册和解压(解压)你应该定义一个知道如何解压gz文件的函数,然后注册这个函数。您可以使用gzip库,例如: import os import r
因此,必须首先使用shutil.register\u archive\u格式进行注册。有人能帮我注册和解压(解压)你应该定义一个知道如何解压gz文件的函数,然后注册这个函数。您可以使用gzip库,例如:
import os
import re
import gzip
import shutil
def gunzip_something(gzipped_file_name, work_dir):
"gunzip the given gzipped file"
# see warning about filename
filename = os.path.split(gzipped_file_name)[-1]
filename = re.sub(r"\.gz$", "", filename, flags=re.IGNORECASE)
with gzip.open(gzipped_file_name, 'rb') as f_in: # <<========== extraction happens here
with open(os.path.join(work_dir, filename), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
shutil.register_unpack_format('gz',
['.gz', ],
gunzip_something)
shutil.unpack_archive("Example.json.gz",
os.curdir,
'gz')
导入操作系统
进口稀土
导入gzip
进口舒蒂尔
def gunzip_something(gzip文件名、工作目录):
“压缩给定的gzip文件”
#请参阅有关文件名的警告
filename=os.path.split(gzip文件名)[-1]
filename=re.sub(r“\.gz$”,“”,filename,flags=re.IGNORECASE)
用gzip.open(gzip文件名,'rb')作为f#in:#这个答案对我很有用。对于希望在循环中执行它的人,考虑到shutl.register\u unpack\u格式(…)
应该只初始化一次;否则,将引发注册表错误。