【问题标题】:TypeError: can only concatenate str (not "float") to str, when there is no float anywhereTypeError:只能将str(不是“float”)连接到str,当任何地方都没有float时
【发布时间】:2020-07-14 07:19:09
【问题描述】:

我尝试做一些 JSON,然后出现此错误 -

Traceback (most recent call last):
  File "D:/Pycharm Projects/gloscrape/whole.py", line 61, in <module>
    data2 = '{"Percent":"' + \
TypeError: can only concatenate str (not "float") to str

我不明白 float 是如何相关的,或者为什么这不起作用... 我认为问题出在我的 JSON 技能上,我想我写错了…… 无论如何,如果有人可以帮助我,我会很高兴!

如果需要更多代码 -

for x in range(len(nums)):
    file = open("updates" + str(x) + ".txt", "a")
    data2 = '{"Percent":"' + \
            element[x] + '", "diff":"' + diff + '"}'
    text = json.dump(data2 + '\n', file)

(代码前面定义的元素和差异)

【问题讨论】:

  • 请将element的内容添加到问题中,并确保我们可以看到数据类型(例如使用repr(element)pprint模块)。
  • 错误信息告诉你element[x] 是一个浮点数,所以element[x] 实际上是一个浮点数?很难说,因为您没有提供element 的定义。也很难理解为什么你从nums 中得到x,但访问的东西看起来不相关。
  • 为什么要手动构建 JSON 字符串,然后将其转储为 JSON???

标签: python json python-3.x types typeerror


【解决方案1】:

不确定你要做什么,但你正在转储一个字符串。让jsonmodule 序列化数据:

import json
nums = element = diff = ['foo', 1, 1.123]  # different types

for x in range(len(nums)):
    file = open("/tmp/updates" + str(x) + ".txt", "a")
    print(file)
    data2 = {"Percent": element[x], "diff": diff}
    text = json.dump(data2, file)

updates2.txt 中的数据:

{"diff": ["foo", 1, 1.123], "Percent": 1.123}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 2020-09-18
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多