i have inp file that needs to read from python data.inp
*Heading
** Job name: inp6_1 Model name: Model-1
*Node
1, 50., 20., 40.
2, 100., 20., 40.
3, 100., 20., 0.
4, 50., 20., 0.
5, 100., 0., 40.
6, 100., 0., 0.
7, 50., 0., 0.
8, 50., 0., 40.
9, 0., 40., 40.
*Element, type=C3D8
1, 82, 336, 712, 294, 1, 15, 168, 46
2, 336, 337, 713, 712, 15, 16, 169, 168
3, 337, 338, 714, 713, 16, 17, 170, 169
*Elset, elset=Set-1, instance=Part-1-1, generate
321, 951, 10
*End Assembly
the purpose is to store all numbers between "*Node" and "*Element" in inp file.
Below is my current code, it is workable, but pretty lengthy because i used with open(filepath, 'r') as file: twice, first time is to get line numer, second time is to read from line and store to numpy array.
I tried to put 2 for loops under with, but it is not working where i only get one line of number from inp file.
my working code:
def findNodes(filepath):
with open(filepath, 'r') as file:
for num, line in enumerate(file,1):
if '*Node' in line:
nodeLineStart = num
if '*Element' in line:
nodeLineEnd = num
xx = np.empty(shape=[1, 4])
with open(filepath, 'r') as file:
for num, lin in enumerate(file, 1):
if nodeLineStart+1 <= num <= nodeLineEnd-1:
text = lin.replace(" ", "")
lines = np.genfromtxt(StringIO(text), delimiter=",").reshape(1, 4)
xx = np.append(xx, lines, axis=0)
return xx
ndarray = findNodes('data.inp')
genfromtxtcall. Check its docs. You could also uswreadlinesto read the whole thing. Just givegenfromtxta slice of that list.genfromtxtis there to cover the case of missing data:numpy.loadtxtis an equivalent function when no data is missing.genfromtxt.genis also more useful when loading columns that vary in dtype, i.e. returning a structured array. With the latest version,loadtxthas a speed advantage.