【发布时间】:2018-06-28 10:38:14
【问题描述】:
我有一个循环函数,每次返回一个复杂的嵌套字典,可以这样简化:
d= {
"key1":"A", "key2":"B", "cumulative score":0.1, "direct score":0.4, "depth":0,
"chain":[
{"key1":"A1", "key2":"B1", "cumulative score":0.2, "direct score":0.5, "depth":1,
"chain":[{"key1":"A11", "key2":"B11","cumulative score":0.3, "direct score":0.6, "depth":2, "chain":[]},
{"key1":"A12", "key2":"B12","cumulative score":0.5, "direct score":0.7, "depth":2, "chain":[]}]
},
{"key1":"A2", "key2":"B2","cumulative score":0.1, "direct score":0.2,"depth":1,
"chain":[None,
{"key1":"A22", "key2":"B22","cumulative score":0.1, "direct score":0.5, "depth":2, "chain":[]}]
}
]
}
我的真实字典可以达到“深度”=10+,并且可以包含更多数据。由于我需要手动检查 excel 中的返回值,我发现将输出窗口复制到剪贴板,然后复制到 excel 可以创建一种清晰的方式来显示数据,如下所示:
所以我想在循环函数的末尾添加这样一个函数来执行此操作。这个我试过了
def add_to_clipboard(text):
import tempfile
with tempfile.NamedTemporaryFile("w") as fp:
fp.write(text)
fp.flush()
command = "pbcopy < {}".format(fp.name)
os.system(command)
我的问题是:我收到以下错误,我不知道将剪贴板上的数据保存到 Excel。 谁能帮忙?谢谢。
TypeError Traceback (most recent call last)
<ipython-input-102-8afb2d14c221> in <module>()
----> 1 add_to_clipboard(result_test)
<ipython-input-101-89cb10853a94> in add_to_clipboard(text)
2 import tempfile
3 with tempfile.NamedTemporaryFile("w") as fp:
----> 4 fp.write(text)
5 fp.flush()
6 command = "pbcopy < {}".format(fp.name)
~\AppData\Local\Continuum\Miniconda3\envs\Battery\lib\tempfile.py in func_wrapper(*args, **kwargs)
481 @_functools.wraps(func)
482 def func_wrapper(*args, **kwargs):
--> 483 return func(*args, **kwargs)
484 # Avoid closing the file as long as the wrapper is alive,
485 # see issue #18879.
TypeError: write() argument must be str, not dict
【问题讨论】:
标签: python excel dictionary nested clipboard