1

Say that I got this ndarray using numpy that I want to write to a text file. :

[[1   2   3   4]
[5   6   7   8]
[9   10   11   12]]

This is my code:

width, height = matrix.shape
with open('file.txt', 'w') as foo:
    for x in range(0, width):
        for y in range(0, height):
            foo.write(str(matrix[x, y]))
foo.close()

The problem is that I get all the lines of the ndarray in just one line, however I want it to be written to the file as this :

1 2 3 4
5 6 7 8
9 10 11 12
singrium
  • 1,946
  • 4
  • 16
  • 36

2 Answers2

3

You can simply iterate over each row:

with open(file_path, 'w') as f:
    for row in ndarray:
        f.write(str(row))
        f.write('\n')
singrium
  • 1,946
  • 4
  • 16
  • 36
Sam Chats
  • 2,291
  • 1
  • 10
  • 29
  • Thank you, with some modifications, your answer was the one I am looking for. I'll consider this as the correct answer. – singrium May 18 '18 at 14:46
  • @singrium Glad to help. What were the modifications you made? Can I include them in my answer? – Sam Chats May 18 '18 at 15:00
1

If you need to preserve the shape as described, I would use the pandas library. This post describes how to do it.

import pandas as pd
import numpy as np

your_data = np.array([np.arange(5), np.arange(5), np.arange(5)])

# can pass your own column names if needed
your_df = pd.DataFrame(your_data) 

your_df.to_csv('output.csv')