从损坏的GZ中提取文件

杰拉德

我的代码段可以从GZ中提取文件,并将其另存为.txt文件,但有时该文件可能包含一些奇怪的文本,从而使提取模块崩溃。

文件中的一些乱码:

我使用的方法:

def unpackgz(name ,path):
    file = path + '\\' +name
    outfilename = file[:-3]+".txt"
    inF = gzip.open(file, 'rb')
    outF = open(outfilename, 'wb')
    outF.write( inF.read() )
    inF.close()
    outF.close() 

我的问题我该如何解决?类似于open(file,errors ='ignore')as fil:的东西因为使用这种方法,我只能提取正常的文件。

编辑第一个问题

def read_corrupted_file(filename):

    with gzip.open(filename, 'r') as f:
        for line in f:
            try:
                string+=line
            except Exception as e:
                print(e)
    return string

newfile = open("corrupted.txt", 'a+')
cwd = os.getcwd()
srtNameb="service"+str(46)+"b.gz"
localfilename3 = cwd +'\\'+srtNameb     
newfile.write(read_corrupted_file(localfilename3))

导致多个错误:像这样

固定为工作状态:

def read_corrupted_file(filename):


    string=''
    newfile = open("corrupted.txt", 'a+')
    try:
        with gzip.open(filename, 'rb') as f:
            for line in f:
                try:
                    newfile.write(line.decode('ascii'))
                except Exception as e:
                    print(e)
    except Exception as e:
        print(e)
cwd = os.getcwd()
srtNameb="service"+str(46)+"b.gz"
localfilename3 = cwd +'\\'+srtNameb 
read_corrupted_file(localfilename3)

print('done')
史蒂芬·米勒

通常,如果文件已损坏,则尝试解压缩文件将引发错误,仅获取数据就无济于事,但是如果您想要停止崩溃,则可以使用try catch。

try:
  pass
except Exception as error:
  print(error)

应用此逻辑后,您可以使用gzip逐行读取,但会有try异常,当遇到损坏的部分时仍可以读取下一行。

import gzip

with gzip.open('input.gz','r') as f:
  for line in f:
    print('got line', line)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章