1

我有一个json文件,其内容如下:-

[
{"time":"56990","device_id":"1","kwh":"279.4"},
{"time":"60590","device_id":"1","kwh":"289.4"},
{"time":"64190","device_id":"1","kwh":"299.4"},
{"time":"67790","device_id":"1","kwh":"319.4"},
]

现在我想在 python 中使用seek和方法一次读取该文件一行。tell我试过这个,但它显示一个错误说not able to decode。我实际上想每隔 15 分钟左右从上次读取的指针读取 json 文件。这是我尝试过的。

last_pointer = 0
with open (FILENAME) as f:
    f.seek(last_pointer)
    raw_data = json.load(f)    // this raw_data should load json starting from the last pointer.
    .....process something.........
    last_position = f.tell()
4

2 回答 2

1

如果您的数据完全按照所示的行排列,您可以通过从文件中逐行读取行、修剪尾随逗号并将结果提供给json.loads. 但也许更好的变体是使用像ijson.

于 2013-09-24T13:07:04.680 回答
0
import json   
import time

with open ('dat') as f:
  line = f.readline()
  while line:
    try:
      raw_data = json.loads(line.strip().strip(','))
      print (raw_data)
      time.sleep(15*60)
    except ValueError:
      pass
    line = f.readline()      
于 2013-09-24T13:27:17.130 回答