Search code examples
pythonclassreadlines

Python reading number of lines


I just wanted to query the best way to read the lines of a text file back into a dict or class object.

The data I've written to a text file is quite crude, so I'm sure there may be better ways of formatting.

Essentially the data looks like this (-- is my comments):

Default_scene --this is the scene name 
0 -- start frame
10 --end frame
--this could be a filepath but is blank
2 --number of records in class object can vary but 2 here
Dave01: --record name 
Dave01: -- namespace
V:/assets/test.fbx --filepath for record
1 -- number of export sets (can vary)
Test:Default_scene_Dave01 0-10 --export set
Test01: --record name
Test01:--namespace
C:/test2.fbx --filepath
0--number of export sets

For instance: if I wanted to read a records data back into an object class, how would i tell the read lines script to read the next 1 or even 2 lines depending on how many export sets there might be?

Many thanks!


Solution

  • You read the line that tells you how many export sets there are first, then read that many more lines to process. Code based on your comments might look like

    with open("data.txt") as f:
        scene_name = next(f).strip()
        start_frame = int(next(f))
        end_frame = int(next(f))
        num_recs = int(next(f))
        for _ in range(num_recs):
            rec_name = next(f).strip()
            namespace = next(f).strip()
            fpath = next(f).strip()
            num_export_sets = int(next(f))
            export_sets = [next(f).strip() for _ in range(num_export_sets)]
            # ...