Search code examples
pythonpython-3.xfile-processing

Read file then stop then continue until given line


Python 3.7 question.

I do have a file looking like this: 1 10 10 10 3 25 29 10 52 55 30 70 70 20 0

where 1 shows there will be 1 line coming, 3 shows 3 will come, 0 marks end of file. How to achieve this?

I've tried

def read_each_course(filename):
    with open(filename, 'r') as f:
        lines = []
        content = f.readlines()
        lines += [x.rstrip() for x in content]
    for i in lines:
        while True:
            if str(i).count(" ") == 0:
                lines_to_read = int(i)
                break
        return lines_to_read, next(i)

but that won't work I get

TypeError: 'str' object is not an iterator
 for the next(i).

My idea was to get a list of lists as the items like: [[1, [10, 10, 10]], [3, [25, 29, 10], [52, 55, 30], [70, 70, 20]]]

BUT, I am unsure if that design is a good idea in general? Or should it then be rather a single linked list as the ultimate goal is that as the 3 numbers are coordinates I'll have to only use the next item such as x2-x1, y2-y1, penalty if left out (additional cost) where total cost is the hyp. of the xy triangle which is fine I can calculate that.


Solution

  • This revision of the answer by RomainL simplifies the logic.

    It makes use of iterators to parse the file.

    def read_each_course(filename):
    
        result = []
        with open(filename) as f:
            it = iter(f)
            while True:
                count = int(next(it))
    
                if count == 0:         # Found the stop marker
                    break
    
                current = [count]
                for _ in range(count):
                    current.append([int(v) for v in next(it).strip().split()])
                result.append(current)
        return result
    
    
    print(read_each_course("file2.txt"))
    

    Output as required.