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

How to extract a file temporarily from a zip file with python 3.5

我正在尝试解析已压缩文件的行。我的测试打印显示第一行都是二进制的。我希望情况并非如此,但我不想在任何硬盘上创建文件,我想暂时提取(文件存在于内存中)以用于解析然后关闭它。很多 zip 文件中有很多小文件,我只需要很短的时间,向 HDD 写入任何数量的文件只会造成垃圾,因此写入驱动器对我来说不是一个好的解决方案。

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 之前,我一直在 "BytesIO(LineList[k])" 行出错。我觉得这几乎就是我需要的,但我从 "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"?>

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

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

详情见Stream/string/bytearray transformations in Python 3