Python Forum

Full Version: Use the write function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone!

I'm mew to Python and I'm trying to write a file with Information I get from a finite element mesh in Ansa. For that I use the Ansa python scripts.
I have a file
fileName="essai_tetra"
file=open(fileName+'.mail','w')
And I have a list of element IDs. I would like to write 9 IDs per line but I really don't know how to do that.
I wrote that
for b in range(len(set_elems_ids)):
 file.write("E%d\n" % list(set_elems_ids)[b])
But then I have one ID per line and I don't know how to get 9.

Would someone know how to do that?

Thanks in advance
Manon
You can try this
with open(filename + '.mail', 'w') as file:
    elems = list(set_elems_ids)
    rows = [elems[i:i+9] for i in range(0, len(elems), 9)]
    for r in rows:
        line = ' '.join('E{:d}'.format(x) for x in r)
        print(line, file=file)
Hi Gribouillis (nice name by the way!)

Thanks for your reply. That's a great idea, it worked fine! I didn't know that the "for in" function could be used that way, thanks!

Manon