Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a list of lists from a file as list of lists in python

Tags:

python

file

list

I collected data in the form of list of lists and wrote the data into a text file. The data in the text file looks like

[[123231,2345,888754],[223467,85645]]

I want to read it back and store in a list of lists in my program. But when I do read() from the file and try creating a flat list then it takes everything as a string and the interpretation changes totally and i am not able to query the result I get after reading as normal list of lists in python.

Can someone help me with reading the file and storing in the same format as list of lists?

Thank you!

like image 880
Richa Sachdev Avatar asked Apr 24 '12 08:04

Richa Sachdev


People also ask

Can you make a list of lists in Python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.

How read data from file to list in Python?

You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method. This method splits strings into a list at a certain character. In the example above, we split a string into a list based on the position of a comma and a space (“, ”).

How do I make a nested list in Python?

Python Nested Lists First, we'll create a nested list by putting an empty list inside of another list. Then, we'll create another nested list by putting two non-empty lists inside a list, separated by a comma as we would with regular list elements.


1 Answers

This looks like valid JSON.

So you can simply do:

import json
with open(myfilename) as f:
    lst = json.load(f)

To store your "list of lists" in a file, do

with open(myfilename, "w") as f:
    json.dump(lst, f)
like image 140
Tim Pietzcker Avatar answered Nov 15 '22 21:11

Tim Pietzcker