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

lea*_*123 7 python json

我通过以下方式将我的Python脚本的输出传输到文件output.txt,该脚本访问实时推文推文:

$python scriptTweet.py > output.txt
Run Code Online (Sandbox Code Playgroud)

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

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

tweetfile = open("output.txt")
pyresponse = json.loads('tweetfile.read()')
print type(pyresponse)
Run Code Online (Sandbox Code Playgroud)

弹出此错误:

    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
Run Code Online (Sandbox Code Playgroud)

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

eum*_*iro 10

'tweetfile.read()'你看到它是一个字符串.你想调用这个函数:

with open("output.txt") as tweetfile:
    pyresponse = json.loads(tweetfile.read())
Run Code Online (Sandbox Code Playgroud)

或读它直接使用json.load,让json readtweetfile本身:

with open("output.txt") as tweetfile:
    pyresponse = json.load(tweetfile)
Run Code Online (Sandbox Code Playgroud)

  • 或者使用`json.load(tweetfile)`.为什么要养狗和自己吠? (7认同)