Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file to a list of lists?

I want to create a list of lists from a file that contains the following data:

101 Rahul
102 Julie
103 Helena
104 Kally

CODE

lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

Output I Want

[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]

Output I m getting

['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']
like image 548
Anuj Vikal Avatar asked Sep 12 '25 18:09

Anuj Vikal


1 Answers

You could read line by line iterating on the handle or using readlines(), splitting each line, appending each result, etc... Fixing your code would require to remove the range loop which just reads the file 3 times (but only effectively reads once the first time), and append the splitted items of the lines, using a list comprehension to be more pythonic:

with open("student_details.txt" , "r+") as f:    
     lis = [line.split() for line in f]

note that the cool thing about line.split() (without parameters) is that it gets rid of the line terminator(s) automatically.

but you can make it simpler: csv module does all the parsing for you:

import csv
with open("student_details.txt" , "r") as f:
   cr = csv.reader(f,delimiter=" ")
   # iterate on rows and generate list of lists:
   result = list(cr)
like image 53
Jean-François Fabre Avatar answered Sep 15 '25 08:09

Jean-François Fabre