【发布时间】:2017-03-22 18:12:34
【问题描述】:
我正在 VOLTTRON 平台中实现 ExternalData 代理,以从 CAISO OASIS 数据库中提取 CSV 数据。 OASIS 返回包含 XML 或 CSV 数据的 .zip 文件。在处理 csv 数据之前,我可以通过修改 _handle_csv 函数来提取存档并将生成的 .csv 打开到文件对象中,从而粗略地获得我想要的 CSV 数据:
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 目录中。任何建议将不胜感激。
【问题讨论】: