Reading data from txt file and storing in dataframe

Viewed 156

I have a txt file with has data like this:

[{"text" : "Random Text" , "location" : "place" , "date" : "01 Jan,2012"}, 
 {"text" : "Similar texts" , "location" : "xyz" , "date": "02 Jan, 2020" },
...}]

How do I read this txt file in python and store the data in a dataframe? Please help.
I tried using various delimiters but the results are pretty messed up.

2 Answers

You just import pandas and add it to a dataframe

import pandas as pd

d = [{"text" : "Random Text" , "location" : "place" , "date" : "01 Jan,2012"}, 
 {"text" : "Similar texts" , "location": "xyz" , "date": "02 Jan, 2020" }]


df = pd.DataFrame(data=d)

df

text    location    date
0   Random Text     place   01 Jan,2012
1   Similar texts   xyz     02 Jan, 2020

For all those, who are still not able to get the solution try this:

import pandas as pd    
import json    
    
with open('file.txt') as f:    
    string = f.read()    
    jsonData = json.loads(string)    
    df=pd.DataFrame(jsonData)    

And if you get

JSONDecodeError: Unterminated string starting at:...

This means your file has some missing a '}' or something else is missing in your txt file.

Related