Skip to content
Advertisement

How to save array (integer) to text file in Python?

I have array of this integer type:

object = [[6, 0, 2, 3, 5, 0], [0, 2, 1, 0, 3, 2], [6, 0, 1, 0, 4, 1], [6, 1, 1, 0, 3, 2], [6, 2, 1, 2, 1, 2]]

How can I save this to an xyz.txt file in this format with 5 lines:

6 0 2 3 5 0 
0 2 1 0 3 2
6 0 1 0 4 1 
6 1 1 0 3 2 
6 2 1 2 1 2

The following code returns the error

with open('xyz.txt', 'w') as txt_file:
    for line in object:
        txt_file.write(" ".join(line) + "n")
TypeError: sequence item 0: expected str instance, int found

Advertisement

Answer

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement