Zip文件的Python问题

时间:2014-03-03 19:32:06

标签: python jar zip

免责声明:编码新手

C:\Python27\python.exe C:/Users/Evolution/PycharmProjects/MCMODVERSION/stuff/main.py
<open file 'C:\\Users\\Evolution\\Desktop\\mods\\AT_StalkerCreepers_1.6.4.jar', mode 'r' at 0x026F6A18>
Traceback (most recent call last):
True
<zipfile.ZipFile object at 0x02736EB0>
  File "C:/Users/Evolution/PycharmProjects/MCMODVERSION/stuff/main.py", line 80, in <module>
<open file 'C:\\Users\\Evolution\\Desktop\\mods\\BC_AdditionalPipes2.6.0-BC4.2.1.jar', mode 'r' at 0x026F6AC8>
    o = t.getdirList()
True
  File "C:/Users/Evolution/PycharmProjects/MCMODVERSION/stuff/main.py", line 36, in getdirList
    self.getModinfo(os.path.join(p, o[n]), 'name')
  File "C:/Users/Evolution/PycharmProjects/MCMODVERSION/stuff/main.py", line 46, in getModinfo
    y = zipfile.ZipFile(x)
  File "C:\Python27\lib\zipfile.py", line 766, in __init__
    self._RealGetContents()
  File "C:\Python27\lib\zipfile.py", line 832, in _RealGetContents
    raise BadZipfile("Truncated central directory")
zipfile.BadZipfile: Truncated central directory

Process finished with exit code 1

正在执行的代码:

def getdirList(self):
    p = 'C:\Users\Evolution\Desktop\mods'
    o = [f for f in listdir(p) if isfile(join(p, f))]
    for mod in range(len(o)):
        print o[mod]
        self.getModinfo(os.path.join(p, o[mod]), 'name')


def getModinfo(self,mod,type):
    """ Types:
    modid, name, description, version, mcversion, url
    updateurl, authors, credits, dependencies """
    x = file(mod)
    print x
    print zipfile.is_zipfile(x)
    y = zipfile.ZipFile(x)
    print y

修正了代码:

def getdirList(self):
    p = r'C:\Users\Evolution\Desktop\mods'
    o = [f for f in listdir(p) if isfile(join(p, f))]
    for mod in range(len(o)):
        print o[mod]
        self.getModinfo(os.path.join(p, o[mod]), 'name')

def getModinfo(self,mod,type):
    """ Types: modid, name, description, version, mcversion, 
    url, updateurl, authors, credits, dependencies """
    try:
        x = open(mod, 'rb')
        y = zipfile.ZipFile(x)
        z = y.read(self.minfo)
        #print z
        #zz = self.parseIt(z, '%s": ' % type, ',')
        #print zz
    except KeyError:
        print "ERROR: %s has no %s file!" % (x, self.minfo)
        print "%s" % "-" * 50
    x.close()

现在我运行一个检查,因为你可以看到zip文件实际上是一个zip文件。超过一半的文件抛出此异常。 .jar和.zip

是的我已手动打开它们,它们没有损坏或锁定或任何东西。我可以做些什么,或者我可以使用另一个库来操纵python中的achrives?

感谢。

1 个答案:

答案 0 :(得分:5)

Zip文件是二进制文件。要正确处理二进制文件,您应该以二进制模式打开文件。

替换以下行:

x = file(mod)

使用:

x = file(mod, 'rb')

BTW,在目录路径中转义\,或使用原始字符串文字。 (这不是问题的直接原因,但有一天逃脱序列会给你带来麻烦)

'C:\\Users\\Evolution\\Desktop\\mods' # escape

r'C:\Users\Evolution\Desktop\mods'    # raw string literal (`r` prefix)