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!
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.
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 (“, ”).
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With