将许多python变量列表保存到Excel工作表中,同时保持定义的变量类型? [英] Saving list of many python variables into excel sheet while simultaneously keeping variable types defined?
问题描述
xlsxwriter可以将变量保存到现有的excel文件中,然后再读取它们,尽管问题是变量以字符串形式存储在我的excel文件中.
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.
假设我有许多具有各种类型(pd.datetimerange,pd.df,np.arrays等)的变量的列表,如果我将它们保存到excel文件中,变量类型将丢失.
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.
此外,还从我的Excel文件中调用了Python脚本,因此如果不编写VBA脚本,我将无法更改其中的任何内容.它将暂时关闭我的工作簿,转储字符(带有腌菜串)并重新打开它.
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.
是否可以从excel文件中检索类型而无需先编写解析函数(该函数将使用excel字符串,并为我提供等效变量类型)?
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)?
推荐答案
根据您的评论,您可以通过将适当的本地字典传递给eval
来获取eval
以正确处理某些模块本地的符号. ,以及您的字符串.这是一个可行的解决方案:
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)
输出:
[123, DatetimeIndex(['2018-12-04', '2018-12-05', '2018-12-06'], dtype='datetime64[ns]', freq='D')]
作为负责人,我也有义务警告您,对于您的应用程序使用eval
是非常不安全的.有 许多
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.
这篇关于将许多python变量列表保存到Excel工作表中,同时保持定义的变量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!