我有一个文件压缩/解压缩系统,我首先检查文件是否已压缩,如果没有,那么我将此文件压缩到tar存档(tar.gz)。然后将压缩的存档上载到服务器。上传后,服务器解压缩文件,并对该文件进行一些处理。
如果压缩服务在压缩文件期间关闭,则会出现问题。结果,tar存档被破坏了。
....
tar = tarfile.open(compress_file_name, "w:gz")
tar.add(file_path, arcname=file_name)
tar.close()
....
为了验证文件的完整性,我试试
try:
f = tarfile.open(file_path) # This should throw CRC error but its not
except Exception, e:
raise e
但事实上python似乎打开文件就好了。为了验证文件是否真的好,我尝试打开文件tar -xvzf <corrupted_archive>
,我得到了
[~/]$ tar -xvzf <corrupted_archive>
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
现在我可以使用subprocess.call(['tar','-xvzf',archive_name])
在python中使用相同的过程,但实际上我用什么pythonic方法来验证文件的完整性。
任何帮助都将受到高度赞赏。
答案 0 :(得分:4)
除非标题已损坏,否则打开文件不会产生任何错误。您需要读取整个文件以显示错误。这不是重要的,这是一个tar.gz,来自GZIP(.gz)部分的CRC足以(希望)揭示错误:
import gzip
with gzip.open(file_path) as g:
try:
while g.read(1024 * 1024):
pass
except IOError as e:
print("Corrupted!", e)