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']
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)
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