python - 在 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”。
有人知道我能做什么吗?
解决方案
试试看:
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)
推荐阅读
- javascript - 根据 Google App 脚本中的另一个单元格更改清除单元格内容
- python-3.x - ReverseNo() 接受 1 个位置参数,但给出了 2 个
- automation - 如何使用 Microsoft Power Automate 在 Outlook 电子邮件正文中嵌入一系列图像?
- python - 在复制其他功能的同时展平熊猫数据框中的嵌套 JSON 列
- powershell - 在没有进度条的远程计算机上使用本地 Powershell 脚本安装 Windows 更新
- python-3.x - 使用 xlsxwriter 中的 add_table() 时如何格式化不同的行
- excel - 尝试制作一个宏来获取用户输入,搜索列标题,然后根据输入按升序对数据进行排序
- excel - 从列数据创建字符串不存储完整数据
- react-bootstrap-typeahead - React-Bootstap-Typeahead:选择菜单时在 onChange() 中手动设置自定义显示值
- firebase - 使用颤振从 Firebase Firestore 中的子集合中获取数据