berkay
berkay

Reputation: 3967

Reading from file into Python data structure

I have a file which has the following format:

[
["unique_id1", {"cc":15, "dd":30}], ["unique_id2", {"cc": 184,"dd":10}], ...
]

I want to directly read the file and put data in a Python data structure. For now, I'm processing using regular expressions. Is there a command that I'm missing to read it directly?

Upvotes: 0

Views: 1719

Answers (3)

Mahi
Mahi

Reputation: 21893

You should use ast.literal_eval(), it turns strings that contain Python objects, into Python objects:

>>> import ast
>>> l = ast.literal_eval('[1, 2, 3]')
>>> type(l)
<class 'list'>
>>> l
[1, 2, 3]

So you would read the data from your file and turn it into a list:

with open('file.txt') as infile:
    data = ast.literal_eval(infile.read())

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20339

You can use literal_eval

import ast
f = open('myfile.txt')
print ast.literal_eval(f.read())

Upvotes: 2

muddyfish
muddyfish

Reputation: 3650

This file format is probably JSON from what you've shown us.

You can parse it by doing

import json
out = json.load(file_object)

Either that or its a literal

out = eval(file_object.read())

OR (Preferred)

import ast
out = ast.literal_eval(file_object.read())

Upvotes: 3

Related Questions