2

So, assuming I have a flattened list (with length = 135) where:

matrix_e = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, ...] 

I'd like to write the elements of the list above into a text file, but I can only have a maximum of 16 elements per line. The output should look like this in the text file:

*Elset, elset = matrix
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,34,35,
36,37,38,

For context I am creating a mesh to be analyzed in Abaqus, and apparently you are only allowed 16 elements per line in the mesh file.

Is it possible to set a while condition when using the ','.join method?

Any ideas?

Aedan
  • 37
  • 4

2 Answers2

3

Function chunks splits list at specific size. By making it a function , we make splitting integers dynamic. i.e. we can change 16 to any other number in future as needed.
We then write it to a file while converting int to str.

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

matrix_e = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]


with open("out.txt", "w") as txtfile:
    for l in list(chunks(matrix_e, 16)):
        txtfile.write("{},\n".format(','.join([str(i) for i in l])))

Contents of "out.txt"

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
33,34,35,36,37,38,39,40,41,42,43,44,45,

Anil_M
  • 10,893
  • 6
  • 47
  • 74
1

First of all, I can't recall that Abaqus required to have only 16 element numbers per line for sets, so you may want to verify that.

In any way, one way to do it is to iterate over the list, 16 elements a time:

import math
n_lines = math.ceil(len(matrix_e)/16)
lines = []

for i in range(n_lines):
    lines.append(','.join([str(x) for x in matrix_e[16*i:16*i+16]]))
Gerges
  • 6,269
  • 2
  • 22
  • 44
  • 2
    Yes there is a 16 element limit. Its Nasty too, you only get a warning buried in the dat file that the extra items have been ignored. – agentp Sep 25 '17 at 15:52
  • 1
    note this answer omits the trailing comma on every line, which actually works fine (and looks better). – agentp Sep 25 '17 at 15:58