使用json.loads将文本文件读回字典

2024-09-27 07:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我将访问实时twitter tweets的Python脚本的输出通过管道传输到文件output.txt,使用:

$python scriptTweet.py > output.txt

最初,脚本返回的输出是一个写入文本文件的字典。

现在我想使用output.txt文件来访问其中存储的tweets。但是,当我使用以下代码使用json.loads()将output.txt中的文本解析为python字典时:

tweetfile = open("output.txt")
pyresponse = json.loads('tweetfile.read()')
print type(pyresponse)

弹出此错误:

    pyresponse = json.loads('tweetfile.read()')
  File "C:\Python27\lib\json\__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

如何将output.txt文件的内容再次转换为字典?


Tags: 文件inpytxtjsonoutput字典lib
1条回答
网友
1楼 · 发布于 2024-09-27 07:26:07

'tweetfile.read()'是一个字符串。要调用此函数:

with open("output.txt") as tweetfile:
    pyresponse = json.loads(tweetfile.read())

或者直接用json.load来读,让jsonreadtweetfile本身上:

with open("output.txt") as tweetfile:
    pyresponse = json.load(tweetfile)

相关问题 更多 >

    热门问题