Home > Blockchain >  How to get the last line from JSON file which contains only tuples in each line
How to get the last line from JSON file which contains only tuples in each line

Time:12-17

can anybody pls tell me what way I need to use to fetch the last line from JSON file which contains tuples?

lst = (('7', '♠'), ('7', '♣')) # this line is generated each time and has new values

For instance, "deals.json" file contains such lines:

[["7", "\u2660"], ["7", "\u2663"]]
[["8", "\u2660"], ["8", "\u2663"]]

Code:

# here I add new line into the file
with open('deals.json', 'a') as f:
    json.dump(lst,f)
    f.write('\n')

# here I want to read the last line and handle it
with open('deals.json') as f:
    json_data = json.load(f)
    print(json_data)

After running this code it works fine but after the 2nd one it failed while trying to read the file and it's obvious:

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 549)

I know how to do that using text file but have no idea how to read the last line in JSON which contains tuples.

CodePudding user response:

Reading just the last line can be achieved like this. Internally the entire file will be read but you don't need to handle that explicitly. If the file was very large then you might need another approach.

import json
with open('deals.json') as f:
    j = json.loads(f.readlines()[-1])
    print(j)

Output:

[['8', '♠'], ['8', '♣']]
  • Related