[Solved] Writing a python Matrix to a text file [closed]


According to the official documentation, writelines writes a list of lines to a file.

str(A) does not create a “list of lines” – obviously, when you print it to the screen – so the very first step should be to create a list-of-lines:

A=[
['-', 'A', 'B', 'C', 'D', 'E'],
['A', '0', '5', '6', '7', '8'],
['B', '5', '0', '6', '7', '8'],
['C', '6', '6', '0', '7', '8'],
['D', '7', '7', '7', '0', '8'],
['E', '8', '8', '8', '8', '0']]

print ([' '.join(row) for row in A])

which shows the 2D list has been flattened into a 1D list, with spaces separating the items:

['- A B C D E', 'A 0 5 6 7 8', 'B 5 0 6 7 8', 'C 6 6 0 7 8', 'D 7 7 7 0 8', 'E 8 8 8 8 0']

and so you can dump it into a file:

with open("MyFile.txt","w") as file1:
    file1.writelines ([' '.join(row)+'\n' for row in A])

(per the documentation, you are required to add a newline at the end yourself) with the required result:

- A B C D E
A 0 5 6 7 8
B 5 0 6 7 8
C 6 6 0 7 8
D 7 7 7 0 8
E 8 8 8 8 0

or, alternatively, using write only:

with open("MyFile.txt","w") as file1:
    file1.write ('\n'.join(' '.join(row) for row in A))

0

solved Writing a python Matrix to a text file [closed]