Question

I am new in programming and with python. So I am facing lots of problem. I need a little help on reading a text file in python.

In my input text file, I have two arrays of data with some strings.

HEAD1
1 0 0
2 3 4
3 3 0
END1

HEAD2
2 3 4
8 7 5
1 0 7
END2

Now I want python to read this file and store this two arrays as 2 arrays or 2 matrices. The array size is not fixed, it can be in any size. Python has to decide the size by the head and end. How can I do it?

I have tried numpy.loadtxt and numpy.getfromtxt.In numpy.getfromtxt, I got error for the strings. And without string it make these 2 arrays into 1 array.

Here is what tried to do, but could not do it....

import math as m
import numpy as np

file_name=input("Input file name(with extension):")
file=open(file_name,'r')

line=file.readline()
while line!= '':
    print(line,end='')
    line=file.readline()

##table=np.loadtxt(file_name)
##print('table=')
##print(table)
##
table2=np.genfromtxt(file_name,comments='#') 
print('table2=')
print(table2) 

No correct solution

OTHER TIPS

Since this format with 'HEAD' and 'END' is not known about by numpy.loadtxt, I think you will have to "chunk" those arrays yourself:

import numpy as np

def tokenizer(fname):
    with open(fname) as f:
        chunk = []
        for line in f:
            if 'HEAD'in line:
                continue
            if 'END' in line:
                yield chunk
                chunk = []
                continue
            chunk.append(line)


arrays = [np.loadtxt(A) for A in tokenizer('yourfile.txt')]

OK.... to read the two arrays I had to change the input file a little. I added a string column in front of every array. I had to do this to let python know that these are two different arrays. Here is the input text file:

    *HEAD1
    N 1 0 0
    N 2 3 4
    N 3 3 0
    *****
    *HEAD2
    E 2 3 4
    E 8 7 5
    E 1 0 7
    *****

Now to read these two arrays from the text file I wrote the following code:

import numpy as np

file_name=input("Input file name(with extension):")

#   read the input file

with open(file_name) as f:
    lines1 = (line for line in f if line.startswith('N'))
    n_table = np.loadtxt(lines1, comments='*',usecols=(1,2,3))
    print('n_table=')
    print(n_table)

with open(file_name) as f:
    lines2=(line for line in f if line.startswith('E'))
    e_table = np.loadtxt(lines2,comments='*',usecols=(1,2,3,4,5))
    print('e_table=')
    print(e_table)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top