PRVS PRVS - 6 months ago 9
Python Question

Parse file in python

I have a file.txt like this:

2
1
Test1
345 678
2
-1123 4456
-1198 8808
1
-7351 6731
-3313 3123
2
Asd2
678 910
3
-1132 4234
-2345 5678
-3721 3128
2
-1321 3213
-2311 3212


And I want to parse this file ignoring the first line and the other indexes: 1 above Test1 and 2 above Test2, and I want to put this in a list like:


[['Test1', '345 678', '2', '-1123 4456', '-1198 8808', '1', '-7351
6731', '-3313 3123'], ['Asd2','678 910','3',...


I start by made this:

with open('file.txt') as f:
for line in f:
l.append(line.split())
print l


But I can't obtain a result like I want... Any help/hint?
Thanks in advance!!

Answer

This is my first approach:

Script:

tests = []
with open('file.txt') as f:
    for line in f:
        if "test" in line.lower():
            tests.append([])
            tests[-1].append(line.strip())
        else:
            if len(tests) > 0:
                tests[-1].append(line.strip())

print tests
# [['Test1', '345 678', '2', '-1123 4456', '-1198 8808', '1', '-7351 6731', '-3313 3123', '2'], ['Test2', '678 910', '3', '-1132 4234', '-2345 5678', '-3721 3128', '2', '-1321 3213', '-2311 3212']]