Python TypeError:预期的字符串或缓冲区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33336160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:12:50  来源:igfitidea点击:

Python TypeError: expected string or buffer

pythonjsonpython-2.7

提问by Jetpylot

Need help. Have a list of data named arglist, example: ['dlink', 'des', '1210', 'c', 24] <-- this what "print" views.

需要帮忙。有一个名为 arglist 的数据列表,例如: ['dlink', 'des', '1210', 'c', 24] <-- 这就是“打印”视图。

And this code:

而这段代码:

sw_info ={"Brand":arglist[0],
        "Model":arglist[1],
        "Hardware":arglist[2],
        "Software":arglist[3],
        "Portsnum":arglist[4]}


print json.dumps(sw_info, open("test", "w"))
z = json.loads(open("test", "r"))
print s

It gives:

它给:

Traceback (most recent call last):
  File "parsetest.py", line 34, in <module>
    z = json.loads(open("test", "r"))
  File "/usr/lib64/python2.6/site-packages/simplejson/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/site-packages/simplejson/decoder.py", line 335, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

Whats wrong?

怎么了?

采纳答案by Sven Festersen

You are trying to load a file object, when json.loads expects a string. You could either use

当 json.loads 需要一个字符串时,您正在尝试加载文件对象。你可以使用

z = json.loads(open("test", "r").read())

or, much better:

或者,更好:

with open("test") as f:
    z = json.load(f)

In the first example, the file is opened, but never closed (bad practice). In the second example, the context manager closes the file after leaving the context block.

在第一个示例中,文件被打开,但从未关闭(不好的做法)。在第二个示例中,上下文管理器在离开上下文块后关闭文件。