elmarolafsson
elmarolafsson

Reputation: 13

How can i read a text file of lists and append into list of lists?

My current code looks something like this:

a_list = []
with open("lists.txt", "r") as f:
    for line in f:
        a_list.append(line)

When i print the a_list, list i get this:

[['["David", 45, 102, 7.5, 0, 17.5, 106, 139, 8.5]', ''],
 [['["Phil", 45, 102, 7.5, 0, 17.5, 106, 139, 8.5]', '']...

What i am looking to get is this:

[["David", 45, 102, 7.5, 0, 17.5, 106, 139, 8.5], 
 ["Phil", 45, 102, 7.5, 0, 17.5, 106, 139, 8.5]]

Programming language is python Any Ideas?

Upvotes: 1

Views: 639

Answers (3)

Kroltan
Kroltan

Reputation: 5156

This looks like a file containing many JSON documents, one per line. You can read it with the json module:

import json

a_list = []
with open("lists.txt", "r") as f:
    for line in f:
        a_list.append(json.loads(line))

Why not the ast module? No reason in this case, but ast loads Python literals (literals can represent strings, numbers, dicts and tuples).

But JSON is another thing entirely, and while superficially both look similar, the differences will be very notable with more complex data (such as Unicode).

Upvotes: 0

Aakash Goel
Aakash Goel

Reputation: 1030

Whenever we write anything in to the text file, its data structure get converted in to string type only. So, when we load/open our text file and wish to retain its original data structure in which we wrote/stored in our file, we need to use ast Module / ****liter_eval inbuilt function in ast** ** .

from ast import literal_eval
file_object= open('lists.txt')
output_list=[]
for line in file_object:
    line=line.strip('\r\n')
    output_list.append(literal_eval(line))
print output_list

Upvotes: 0

Satyadev
Satyadev

Reputation: 643

You have to use a package called ast. Try the following after your code snippet:

import ast

final_list = [ast.literal_eval(j) for i in a_list for j in i] 

Your txt file has converted the list into a str , the above mentioned package does somewhat of an exexute. Feel free to read up when you have time. Hope it helps!

Upvotes: 1

Related Questions