首页 > 解决方案 > 在 Python 中打开 .txt 文件作为 Json 文件

问题描述

我已经搜索了一整天的 Stackoverflow,但我似乎无法找到我的问题的答案。我也尝试了几件事,但没有奏效;我认为解决方案并不难,所以也许你们中的一个可以帮助我。

.txt 文件格式如下:

{"text": "x x x x"}
{"text": "x x x x"}
{"text": "x x x x"}

它应该是以下代码:

with open("/Python map/Jsons scraped.txt") as jsonfile:    
          test2 = json.load(jsonfile)

但是,这会导致以下错误(UnsupportedOperation:不可读)

我还尝试添加 'w'、'r'、'a+' 和其他阅读形式:

with open("/Python map/Jsons scraped.txt") as jsonfile:    
          test2 = json.load(jsonfile, 'w')

这会导致以下错误。添加“w”后,错误仍然是“UnsupportedOperation:不可读”。但是,使用 'r' 而不是 'w' 时,错误会变成“JSONDecodeError: Expecting value”。

有人知道我能做什么吗?

标签: pythonjson

解决方案


试试看:

import json

with open('hello world/smth.txt', 'r+') as f:
    print(json.load(f))

当您在路径的开头添加斜杠时,它会按绝对路径查找,尝试将其删除或使用如下:

'./hello world/smth.txt'

此外,您使用的 json 无效,我将逐行移动并将其转换为 json,例如:

import json

with open('hello world/smth.txt', 'r') as f:
    result = [json.loads(x) for x in f.readlines()]

print(result)

推荐阅读