Search code examples
pythonpython-3.xlistread-text

Reading text file and assigning it to a variable in Python


I am trying to read a text file, which has the following structure:

BUS 0   
0   1   2   3   
0   4   1   9   2   3   
BUS 1  
0   1   9   2   3   
0   1   2   3   
0   1   2   3   

It is basically a 3D list, where the nested 2D lists are matrices with an unequal number of columns and rows. The first index is denoted by the string "BUS", followed by a number. The next lines are correspond to a 2D list, with each line being a list, until the next "BUS" string. I need to assign the numbers in this text file to a 3D list in Python. The example given above should translate to :

[ [ [0,1,2,3],[0,4,1,9,2,3] ], [ [0,1,9,2,3],[0,1,2,3],[0,1,2,3] ] ]

Thanks in advance for any help.


Solution

  • You can try the following:

    data = []
    
    with open("file.wtv") as file_in:
        for line in file_in:
            try:
                row = [*map(int, line.strip().split())]
                data[-1].append(row)
            except ValueError:
                data.append([])
    
    data
    # [[[0, 1, 2, 3], [0, 4, 1, 9, 2, 3]], 
    #  [[0, 1, 9, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]