Saving list of many python variables into excel sheet while simultaneously keeping variable types defined?

落花浮王杯 提交于 2019-12-03 11:21:41

问题


It's possible with xlsxwriter to save variables to existing excel files and read them after, though the problem is that the variables are stored as strings in my excel file.

Let's say I have a list of many different variables with various types (pd.datetimerange, pd.df, np.arrays, etc.), if I save them to the excel file the variable type would be lost.

Also the Python script is called from my Excel file so I can't change anything in it without writing a VBA script. Which would temporarily close my workbook, dump the chars (with say pickle strings) and reopen it.

Is it possible to retrieve the types from the excel file without writing a parsing function first (which would take the excel string and yield me with the equivalent variable type)?


回答1:


As per your comment, you can get eval to correctly process the symbols that are local to some module by passing the appropriate dict of locals into eval, along with your string. Here's a workable solution:

import pandas as pd

def getlocals(obj, lcls=None):
    if lcls is None: lcls = dict(locals().items())

    objlcls = {k:v for k,v in obj.__dict__.items() if not k.startswith('_')}
    lcls.update(objlcls)

    return lcls

x = "[123,DatetimeIndex(['2018-12-04','2018-12-05', '2018-12-06'],dtype='datetime64[ns]', freq='D')]"
lcls = getlocals(pd)

result = eval(x, globals(), lcls)
print(result)

Output:

[123, DatetimeIndex(['2018-12-04', '2018-12-05', '2018-12-06'], dtype='datetime64[ns]', freq='D')]

As a Responsible Person, it is also my duty to warn you that using eval for your application is ridiculously unsafe. There are many discussions of the dangers of eval, and none of them suggest there's a way to completely mitigate those dangers. Be careful if you choose to use this code.



来源:https://stackoverflow.com/questions/53663758/saving-list-of-many-python-variables-into-excel-sheet-while-simultaneously-keepi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!