如何使用python3.5从zip文件中临时提取文件

2024-09-30 06:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析一个压缩文件的行。我的测试结果显示第一行都是二进制的。我希望不是这样,但我不想在任何硬盘上创建一个文件,我想暂时提取(文件存在于内存中)用于解析,然后关闭它。在很多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之前,我一直在“BytesIO(LineList[k])”行中出错。我觉得这几乎就是我需要的,但是我从“print(BytesIO(LineList[k])”看到的是二进制的,我想看到文本。我怀疑问题出在“工作文件”上=拉链打开(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"?>

Tags: 文件inforifmatchprintx00硬盘

热门问题