Search code examples
pythonnumpymatrixtextabaqus

Python 3.x Reading files with headers (data between identified headers)


I'm using Python 3.4, and I have NunPy/SciPy already installed. I need to read a text file with the following structure:

*Node
  1, -0.600000024,   1.20000005,           0.
  2, -0.600000024,  0.300000012,           0.
  3, -0.480560571,    0.1741862,           0.
  4, -0.335430175, 0.0791868418,           0.
  (...)
  n, x, y, z
*Element
  1, 1, 2, 3, 4
  2, 5, 6, 7, 8
  (...)
  n, a, b, c, d

From this txt file I need to create a matrix called "node", which contains the info between *Node and *Element, I mean, it has to have 4 columns and n lines, for example:

node=array([1, -0.600000024, 1.20000005, 0.],[2, -0.600000024, 0.300000012, 0.], [3, -0.480560571, 0.1741862, 0.],[4, -0.335430175, 0.0791868418, 0.], [n, x, y, z])

And another matrix called "element", which contains the lines after *Element:

element=array([1, 1, 2, 3, 4], [2, 5, 6, 7, 8], [n, a, b, c, d])

Indeed, I need just to "read" the text file and write this content into two matrices. However, I have to separete the information that is under *Node from that under *Element. I have to have two matrices, one with nodes and other with elements... But I'm new at Python and have no idea on how to read a text file in this way and generate those matrices...

I'd appreciate any help/example. Thanks a lot!


Solution

  • Creating a list with the lines in your file, then creating sub lists starting and stopping at the index if '*Node' and '*Element' should work for you:

    r=[]
    s = open('File.txt')
    For line in s:
      r.append(line.strip('\n'))
    Node=[]
    Element=[]
    For i in r[r.index('*Node')+1:r.index('*Element')]:
      Node.append(map(float,i.split(',')))
    For j in r[r.index('*Element')+1:]:
      Element.append(map(int, j.split(','))
    Node=np.array(Node)
    Element=np.array(Element)