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)
5 Answers
+ 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.
+ 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]
+ 2
Can you describe how your file looks and how your list is supposed to look at the end?
0
file -
1 David male
2 Helen female
3 Mark male
list-
[[1 ,'david','male'],[2,'helen','female'],[3,'mark,'male']]
0
thanks a lot . it almost got me the answer except in the end I get an extra empty list