In the text file, the data is:
# 2.1,-3.1 -0.7,4.1 # 3.8,1.5 -1.2,1.1
I want to read it into nested list and the list should have data in the form like: [[[2.1,-3.1],[-0.7,[4.1]],[[3.8,1.5],[-1.2,1.1]]]
That is, Every # starts a inner list Every new line starts a inner list. The next # closes previous inner list and creates new inner list.
Also The data is in string format and it needs to be converted to float values. I have written the following code:
def read_weights(file_name): # 1 Mark file = open(file_name) res =  for line in file: m =  if '#' in line.strip(): pass else: x = line.split() for i in x: y = i.split(',') i = 0 for c in y: m.insert(i, float(c)) i = i + 1 if m != : res .append(m) file.close() return res w_example = read_weights('example_weights.txt') print(w_example)
The output is: [[2.1, -3.1], [-0.7, 4.1], [3.8, 1.5], [-1.2, 1.1]]
After every #, i am not been able to create a inner list
This is one approach using negative indexing to access the last inserted list.
result =  with open(filename) as infile: for line in infile: line = line.strip() if line == "#": result.append() else: line = list(map(float, line.split(","))) result[-1].append(line) print(result)
[[[2.1, -3.1], [-0.7, 4.1]], [[3.8, 1.5], [-1.2, 1.1]]]