7

I use

np.savetxt('file.txt', array, delimiter=',')

to save array to the file separated with comma. It looks like:

1, 2, 3
4, 5, 6
7, 8, 9

How can I save the array into the file shown as it is in the numpy format. In other words, it looks like:

[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
2
  • 5
    why are you trying to save it like that? It'll just make it much more difficult to read back in when you want to use the data... Commented Apr 2, 2014 at 19:47
  • @MattDMo, I want to use the array somewhere else with only stdin feasible but not read from disk. I plan to use the naive copy+paste approach. Commented Apr 2, 2014 at 19:53

4 Answers 4

7
In [38]: x = np.arange(1,10).reshape(3,3)    

In [40]: print(np.array2string(x, separator=', '))
[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

To save the NumPy array x to a file:

np.set_printoptions(threshold=np.inf, linewidth=np.inf)  # turn off summarization, line-wrapping
with open(path, 'w') as f:
    f.write(np.array2string(x, separator=', '))
Sign up to request clarification or add additional context in comments.

3 Comments

@DSM: Thank you; I simply didn't know it was there.
thanks for your reply. When I tried to use savetxt on tmp = np.array2string(x, separator=', '), it gives me "tuple index out of range" error. Can you please show me how to save your result into text file? Thanks
@ChuNan: I've added some code to show how to save x to a file. That should work for moderate-sized arrays. One drawback however is that if x is huge, np.array2string would generate one gigantic string. That's not memory-friendly. In that case, it would be better to iterate through the rows of x and print them chunks at a time.
3

You can use the first format for copy-pasting as well:

>>> from io import BytesIO
>>> bio = BytesIO('''\
... 1, 2, 3
... 4, 5, 6
... 7, 8, 9
... ''') # copy pasted from above
>>> xs = np.loadtxt(bio, delimiter=', ')
>>> xs
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

Comments

2
import sys

file = "<you_file_dir>file.txt"

sys.stdout = open(file, 'w')

d = [1,2,3,4,5,6,7,8,9]
l__d1 = d[0:3]
l__d2 = d[3:6]
l__d3 = d[6:9]

print str(l__d1) + '\n' + str(l__d2) + '\n' + str(l__d3)

Comments

0
import numpy as np
def writeLine(txt_file_path, txtArray: list):
   l = len(txtArray)
   counter = 0
   with open(txt_file_path, 'a', encoding='utf-8') as f:
       for item in txtArray:
           counter += 1
           row = [str(x) for x in item]
           fstr = '\t'.join(row)+'\n' if counter<l else '\t'.join(row)
           f.writelines(fstr)

x = np.arange(16).reshape(4,4)
writeLine('a.txt',x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.