Home > Software design >  Reading text file and assigning it to a variable in Python
Reading text file and assigning it to a variable in Python

Time:10-27

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.

CodePudding user response:

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]]]

CodePudding user response:

You need to write a simple parser:

test = '''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'''

out = []
for line in test.split('\n'):
    if line.startswith('BUS'):
        out.append([])
    else:
        out[-1].append(list(map(int, line.split())))

output:

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

from a file:

with open('file.txt') as f:
    out = []
    for line in f:
        if line.startswith('BUS'):
            out.append([])
        else:
            out[-1].append(list(map(int, line.split()))) 
  • Related