迭代多行

时间:2017-02-20 12:42:07

标签: python

我有一个大文本文件,即pre.txt,我想要使用python在多行上读取feat_left点。这是文本文件的快照。

{
  "outputs": {
    "/home/113267806.jpg": {
      "feat_left": [
        2.369331121444702, 
        -1.1544183492660522
      ], 
      "feat_right": [
        2.2432730197906494, 
        -0.896904468536377
      ]
    }, 
    "/home/115061965.jpg": {
      "feat_left": [
        1.8996189832687378, 
        -1.3713303804397583
      ], 
      "feat_right": [
        1.908974051475525, 
        -1.4422794580459595
      ]
    }, 
    "/home/119306609.jpg": {
      "feat_left": [
        -0.7765399217605591, 
        -1.690917730331421
      ], 
      "feat_right": [
        -1.1964678764343262, 
        -1.9359161853790283
      ]
    }, 

1 个答案:

答案 0 :(得分:3)

阅读json并像这样迭代,

import json
data = json.load(open('file_name.json'))
for val in data['outputs'].values():
     print(val['feat_left'])

结果将是这样的,

[-0.7765399217605591, -1.690917730331421]
[2.369331121444702, -1.1544183492660522]
[1.8996189832687378, -1.3713303804397583]

修改 您可以像这样使用图像路径,

for key,val in a['outputs'].items():
         print(key,val['feat_left'])

它会给这个谎言

('/home/119306609.jpg', [-0.7765399217605591, -1.690917730331421])
('/home/113267806.jpg', [2.369331121444702, -1.1544183492660522])
('/home/115061965.jpg', [1.8996189832687378, -1.3713303804397583])