Rya*_*ard 21 python compression gzip
我有一个Python程序,它将把文本文件作为输入.但是,其中一些文件可能是gzip压缩的.
是否存在跨平台,可以从Python方式使用以确定文件是否压缩为gzip?
以下是可靠的还是一个普通的文本文件'不小心'看起来像gzip一样足以让我得到误报?
try:
gzip.GzipFile(filename, 'r')
# compressed
# ...
except:
# not compressed
# ...
Run Code Online (Sandbox Code Playgroud)
"是否存在跨平台,可以从Python方式使用以确定文件是否压缩为gzip?"
接受的答案让我获得了90%的可靠解决方案(测试前两个字节1f 8b),但没有说明如何在Python中实际执行此操作.这是一种可能的方式:
import binascii
def is_gz_file(filepath):
with open(filepath, 'rb') as test_f:
return binascii.hexlify(test_f.read(2)) == b'1f8b'
Run Code Online (Sandbox Code Playgroud)
测试gzip 文件的幻数是唯一可靠的方法。但是,从 python3.7 开始,不再需要自己比较字节。gzip 模块将为您比较字节,如果不匹配则引发异常!
从python3.7开始,这有效
import gzip
with gzip.open(input_file, 'r') as fh:
try:
fh.read(1)
except OSError:
print('input_file is not a valid gzip file by OSError')
Run Code Online (Sandbox Code Playgroud)
从 python3.8 开始,这也有效:
import gzip
with gzip.open(input_file, 'r') as fh:
try:
fh.read(1)
except gzip.BadGzipFile:
print('input_file is not a valid gzip file by BadGzipFile')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23143 次 |
| 最近记录: |