-4

The format of the text file:

{

"id":2,

"name":"hari"

}

{

"id":4,

"name":"kumar"

}

How to read this file? It consists of dictionaries. It is not a json file.

  • it looks like a JSON file tries using JSON lib to load the file in python try using json.loads() – vineeth560 Jan 22 '18 at 03:59
  • Please read the [How to ask](https://stackoverflow.com/help/how-to-ask) section and provide a [Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve) of your attempt. – r.ook Jan 22 '18 at 04:00

4 Answers4

0

As mentioned earlier, this is not a uniform set of data that is easy to parse.

  1. There are two sets of {} independent of each other. You need to decide to either combine the two and read as 1 JSON with 2 Dicts (python) in them OR 2 JSONs of 1 Dict.
  2. JSONs usually have values in double quotes (" "), not single quotes (' ') for strings. Here, it appears the data is trying to say 'all values are in single quotes' and 'all variables/keys are double quotes'. JSON does not like single quotes for values

From this, it appears that the 'assignment' is for you to make a custom reader. You need to parse the data line by line. Then you have to decide: Are you going to make it a JSON object to convert to dict? Or are you going to translate the data immediately. OR what other means you want to us. Decide and if you fail with your code, then we can help you once we see the code. Otherwise we are speculating what you want to do or doing all the work for you.

Otherwise, please check documents on "how to read files" or "open files"

0

If it's not json format, here's my answer:

import ast

def find(s, ch):
    # returns all indexes of occurrences of char ch in string s
    return [i for i, ltr in enumerate(s) if ltr == ch]

# 1. Load your txt file as string
with open('file.txt') as f:
    txt = f.read()

# 2. Find occurrences of chars { and }
start = find(txt, '{')
end = find(txt, '}')

# 3. Evaluate the string between corresponding occurrences of { and }
for s, e in zip(start, end):
    a_python_dict = ast.literal_eval(txt[s:e+1])
    print(a_python_dict)

I took the find method here.

rickyalbert
  • 2,552
  • 4
  • 21
  • 31
0

Custom parser implementation. It collects string between { and }, and then loads it as JSON. If you want to load nested dictionaries you need to add brackets counter.

import json


result = []

with open('file.txt') as f:

    text_block = ''
    for line in f:
        text = line.strip()
        if text == '{':
           text_block = text
        elif text == '}':
            text_block += text
            result.append(json.loads(text_block))
        else:
            text_block += text

print(result)

Output:

[{'id': 2, 'name': 'hari'}, {'id': 4, 'name': 'kumar'}]
Diman
  • 418
  • 3
  • 10
-1

It seems to me that your text is in a json format! If that is your case, the answer is very simple:

import json

with open('file.txt', 'r') as f:
    data = json.loads(f.read())
rickyalbert
  • 2,552
  • 4
  • 21
  • 31