jpcgandre
jpcgandre

Reputation: 1505

create a second row for a list in python and write list to txt file

I have a code which at a stage has the following line:

n_brace.extend([numEL, valueLX[j],valueB[jj], el[2]])

This line is included in a for loop so it produces for example:

n_brace:
[367, '62', '141', '142', 369, '124', '156', '155', 379, '344', '266', '265', 381, '313', '251', '252']

However I want it to be instead:

n_brace:
[[367, '62', '141', '142'], [369, '124', '156', '155'], [379, '344', '266', '265'], [381, '313', '251', '252']]

At the end of the program I open a file and want to write n_brace to it:

fbrace = open("C:/Abaqus_JOBS/brace.txt", 'w')
fbrace.write(n_brace)

I'd like the result to be:

367, 62, 141, 142
369, 124, 156, 155
379, 344, 266, 265
381, 313, 251, 252

But I get the following error:

TypeError: expected a character buffer object

Any ideas?

Upvotes: 1

Views: 198

Answers (1)

NPE
NPE

Reputation: 500257

Change extend() to append():

n_brace.append([numEL, valueLX[j],valueB[jj], el[2]])

As for the writing (assuming Python 2.x):

with open("C:/Abaqus_JOBS/brace.txt", 'w') as fbrace:
    for row in n_brace:
        print >>fbrace, ', '.join(map(str, row))

Upvotes: 3

Related Questions