0

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?

1
  • 1
    That looks like json Commented Aug 16, 2015 at 17:50

3 Answers 3

3

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())
Sign up to request clarification or add additional context in comments.

9 Comments

json format is okay, if you could write how can I loop through efficiently, I will appreciate that.
You don't have to use a for loop for JSON, you just read it in and it just works.
I understand, but I need to access some uniqueids and process them.
then use a normal for loop to iterate through the list created and access the uid with value[0]
not sure why this got no votes, you should parse json with the json lib
|
2

You can use literal_eval

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

Comments

0

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())

1 Comment

I guess the problem is after reading the file, processing them. Thanks, this helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.