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.
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.
As mentioned earlier, this is not a uniform set of data that is easy to parse.
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"
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.
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'}]
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())