您的代码逻辑存在几个问题。
ss = s.read()
读取整个文件s
成单个字符串。下一行
for line in ss:
迭代每个特点在那根弦上,一根一根。所以在每个循环上line
是单个字符。在
line = ss[7:]
您将获取除前 7 个字符(位置 0 到 6,含)之外的整个文件内容,并替换以前的内容line
接着就,随即。进而
T.append(json.loads(line))
尝试将其转换为 JSON 并将结果对象存储到T
list.
这是一些可以实现您想要的功能的代码。我们不需要将整个文件读入字符串中.read
,或进入行列表.readlines
,我们可以简单地将文件句柄放入 for 循环中,该循环将逐行迭代文件。
我们使用一个with
语句打开文件,这样当我们退出时它会自动关闭with
块,或者是否存在 IO 错误。
import json
table = []
with open('simple.json', 'r') as f:
for line in f:
table.append(json.loads(line[7:]))
for row in table:
print(row)
output
{'color': '33ef', 'age': '55', 'gender': 'm'}
{'color': '3444', 'age': '56', 'gender': 'f'}
{'color': '3999', 'age': '70', 'gender': 'm'}
我们可以通过构建来使其更加紧凑table
在列表理解中列出:
import json
with open('simple.json', 'r') as f:
table = [json.loads(line[7:]) for line in f]
for row in table:
print(row)