如何使用python 3.5从zip文件中临时提取文件

时间:2016-05-17 05:26:43

标签: python xml io zip python-3.5

我正在尝试解析已经压缩的文件的行。我的测试打印显示第一行全部是二进制。我希望这不是这种情况,但我不想在任何HDD上创建文件,我想暂时提取(文件存在于内存中)以用于解析然后关闭它。很多zip文件中都有很多小文件,我只需要简单地写一下,写任何数量的硬盘只会让事情变得简单,所以写入驱动器对我来说不是一个好的解决方案。

ListOfZipFiles = os.listdir(AllFileLocation)
i=0
for zipIndex in ListOfZipFiles:
    strIndex=ListOfZipFiles[i].find("_")
    if strIndex > 0:
        #Next line gets the date from the file name in the format saved
        FileDate=datetime.strptime(ListOfZipFiles[i][0:strIndex],"%Y-%m-%d")
        if FileDate >= StartTimeFrame and FileDate < EndingTimeFrame:
            print(AllFileLocation + "\\" + ListOfZipFiles[i])
            Zip = zipfile.ZipFile(AllFileLocation + "\\" + ListOfZipFiles[i],"r")
            FileList=Zip.namelist()
            j=0
            for fileIndex in FileList:
                print(FileList[j])
                WorkFile=Zip.open(FileList[j],"r")
                Data=WorkFile.read()
                WorkFile.close()
                LineList=Data.splitlines()

                #Determine if this is a result for our target
                k=0
                PodProjectLine=0
                for lineIndex in LineList:
                    print(BytesIO(LineList[k]))
                    if PodProjectIndentifier in BytesIO(LineList[k]):
                        PodProjectLine=k
                        lineIndex=len(LineList)
                    k+=1

                if PodProjectLine==0:
                    #shit happened, handle it
                    print("PodProjectLine=0, this should not happen.")
                else:
                    match=re.search(PodProjectIndentifier,LineList[PodProjectLine])
                    PodProjectStart=match.end(1)
                    match=re.search(AttributeLineEnder,LineList[PodProjectLine])
                    PodProjectEnd=match.start(1)
                    PodProject=LineList[PodProjectStart:PodProjectEnd]
                    print(PodProject)
                j+=1
    i+=1

我在“BytesIO(LineList [k])”行中遇到错误,直到我收录了BytesIO。我觉得这几乎是我所需要的,但我从“print(BytesIO(LineList [k]))”看到的是二进制文件,我希望看到文本。我怀疑问题是“WorkFile = Zip.open(FileList [j],”r“)”但我不知道。我看到文件的第一行是:

b'\xff\xfe<\x00?\x00x\x00m\x00l\x00 \x00v\x00e\x00r\x00s\x00i\x00o\x00n\x00=\x00"\x001\x00.\x000\x00"\x00 \x00e\x00n\x00c\x00o\x00d\x00i\x00n\x00g\x00=\x00"\x00u\x00t\x00f\x00-\x001\x006\x00"\x00?\x00>\x00'

应该是:

<?xml version="1.0" encoding="utf-16"?>

1 个答案:

答案 0 :(得分:1)

输出字符串中的b'...'表示输出是字节流。转换它应该是:

print(s.decode('utf-16'))

有关详细信息,请参阅Stream/string/bytearray transformations in Python 3

相关问题