2017-03-22 52 views
0

我正在VOLTTRON平台中实施ExternalData代理以从CAISO OASIS数据库中提取CSV数据。 OASIS返回包含XML或CSV数据的.zip文件。我能粗制滥造前处理CSV数据得到我想要通过修改_handle_csv函数提取存档,并打开生成的.csv到一个文件对象的CSV数据:我正在实施VOLTTRON中的ExternalData代理以从CAISO OASIS获取数据

def _handle_csv(self, headers, request, url, source_topic, source_params): 
    key_column = source_params.get("key", "") 
    flatten = source_params.get("flatten", False) 
    parse_columns = source_params.get("parse", []) 

    # I am expecting a zip archive containing a csv file 
    # so this is a workaround to read the zipfile and extract the csv 
    # by creating a file object with open() after extracting 
    # TODO find another way to get data w/o opening file so we dont 
    # have to do housekeeping 
    z = zipfile.ZipFile(StringIO(request.content)) 
    fname = z.namelist() 
    z.extractall() 
    file_obj = open(fname[0], 'r') 

    # orig. file object assignment assuming request already in csv format 
    # file_obj = StringIO(request.content) 

我想找到一个更好的方法来做到这一点,并避免必须执行多余的内务管理,例如关闭.csv并将其删除,以便文件不会堆积在agent-data目录中。任何建议,将不胜感激。

回答

0

使用ZipFile.open方法。 Docs

然后,您可以将生成的文件(如对象)传递给CSV解析器。

file_obj = z.open(fname[0]) #Remove the extractall() call and this should do the trick. 
+0

谢谢凯尔,我一定跳过了python文档。我会尝试。 – jmattfeld

+0

不客气。这可能是添加到代理的好功能。你介意创建一个问题在这里要求这个功能:https://github.com/VOLTTRON/volttron/issues –