Python: 将特殊文件解压缩到内存中并将它们放入 DataFrame

Python: unziping special files into memory and getting them into a DataFrame

我对我在 Python 中编写的代码非常困惑,我是初学者,也许真的很容易,但我就是看不到它。任何帮助,将不胜感激。所以提前谢谢你:)

这是问题所在:我必须将一些具有特殊扩展名 .fen 的特殊数据文件读入 pandas DataFrame.This .fen 文件位于包含 .fenx 的压缩文件中。 fen 文件和一个 .cfg 配置文件。

在我编写的代码中,我使用 zipfile 库来解压缩文件,然后将它们放入 DataFrame 中。这段代码如下

import zipfile
import numpy as np
import pandas as pd

def readfenxfile(Directory,File):

    fenxzip = zipfile.ZipFile(Directory+ '\' + File, 'r')
    fenxzip.extractall()
    fenxzip.close()

    cfgGeneral,cfgDevice,cfgChannels,cfgDtypes=readCfgFile(Directory,File[:-5]+'.CFG')
    #readCfgFile redas the .cfg file and returns some important data. 
    #Here only the cfgDtypes would be important as it contains the type of data inside the .fen and that will become the column index in the final DataFrame.
    if cfgChannels!=None:        
        dtDtype=eval('np.dtype([' + cfgDtypes + '])')
        dt=np.fromfile(Directory+'\'+File[:-5]+'.fen',dtype=dtDtype)
        dt=pd.DataFrame(dt)
    else:
        dt=[]

    return dt,cfgChannels,cfgDtypes

现在,extract() 方法将解压缩的文件保存在硬盘中。 .fenx 文件可能非常大,因此存储(然后删除它们)的速度非常慢。我想做和现在一样的事情,但是将 .fen 和 .cfg 文件放入内存,而不是硬盘。

我已经尝试过 fenxzip.read('whateverthenameofthefileis.fen') 之类的方法以及 zipfile 库中的 .open() 等其他方法。但是无论如何我都无法将 .read() returns 放入 numpy 数组中。

我知道这个问题很难回答,因为您没有文件来尝试看看会发生什么。但如果有人有任何想法,我会很高兴阅读它们。 :) 非常感谢!

这是我最终找到的解决方案,以防对任何人都有帮助。它使用临时文件库在内存中创建临时对象。

import zipfile
import tempfile
import numpy as np
import pandas as pd

def readfenxfile(Directory,File,ExtractDirectory):


    fenxzip = zipfile.ZipFile(Directory+ r'\' + File, 'r')

    fenfile=tempfile.SpooledTemporaryFile(max_size=10000000000,mode='w+b') 
     fenfile.write(fenxzip.read(File[:-5]+'.fen'))
     cfgGeneral,cfgDevice,cfgChannels,cfgDtypes=readCfgFile(fenxzip,File[:-5]+'.CFG')

    if cfgChannels!=None:        
        dtDtype=eval('np.dtype([' + cfgDtypes + '])')
        fenfile.seek(0)
        dt=np.fromfile(fenfile,dtype=dtDtype)
        dt=pd.DataFrame(dt)
    else:
        dt=[]
    fenfile.close()
    fenxzip.close()    
    return dt,cfgChannels,cfgDtypes