Python TypeError:预期的字符串或缓冲区 [英] Python TypeError: expected string or buffer
本文介绍了Python TypeError:预期的字符串或缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要帮助. 有一个名为arglist的数据列表,例如: ['dlink','des','1210','c',24]<-这就是打印"视图.
Need help. Have a list of data named arglist, example: ['dlink', 'des', '1210', 'c', 24] <-- this what "print" views.
这段代码:
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
它给出:
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
怎么了?
推荐答案
当json.loads需要一个字符串时,您正在尝试加载文件对象.您可以使用
You are trying to load a file object, when json.loads expects a string. You could either use
z = json.loads(open("test", "r").read())
或者更好:
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.
这篇关于Python TypeError:预期的字符串或缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文