0

Read contents of a file and create nested list .

I have tried doing this in so many ways but none of them worked .example the below code .I don't know how to do this at all. can someone please help fin=open("filename.txt",'r') line=fin.readlines() fin.close() l=[] for i in range(3): for j in range(3): l[i].append(line) print(l)

19th Dec 2018, 2:43 PM
Mara
5 odpowiedzi
+ 3
try it like this: ... lines = fin.readlines() ... for line in lines: l.append(line.split()) Explanation: readlines separates your file by '\n', so afterwards you have a list with the lines as one string each. By splitting this line (by ' '), you get a list of words, and this list you append to your l list. Oh yeah, and in the end you have to turn your numbers which are still strings into actual numbers: for i in range(len(l)): l[i][0] = int(l[i][0]) But then it should work. ;) Keep me posted.
19th Dec 2018, 2:56 PM
HonFu
HonFu - avatar
+ 3
Ah, probably you got a newline at the end of the file. You can put this line into your code: if lines[-1] == '': del lines[-1]
19th Dec 2018, 3:06 PM
HonFu
HonFu - avatar
+ 2
Can you describe how your file looks and how your list is supposed to look at the end?
19th Dec 2018, 2:49 PM
HonFu
HonFu - avatar
0
file - 1 David male 2 Helen female 3 Mark male list- [[1 ,'david','male'],[2,'helen','female'],[3,'mark,'male']]
19th Dec 2018, 2:54 PM
Mara
0
thanks a lot . it almost got me the answer except in the end I get an extra empty list
19th Dec 2018, 3:00 PM
Mara