首页 > 解决方案 > 如何将复杂的嵌套字典保存到剪贴板,然后保存到 Excel

问题描述

我有一个循环函数,每次返回一个复杂的嵌套字典,可以这样简化:

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

标签: pythonexceldictionarynestedclipboard

解决方案


错误说您只能写入文件中的字符串对象,这里的文本变量是字典。主要是 write() 只接受字符串对象。所以你可以将你的字典对象转换成字符串

import json
jsonStr = json.dumps(text)
print(type(jsonStr ))
fp.write(text)

推荐阅读