2

I'm trying to write a numpy array into txt file:

a = numpy.array([1,2,3])
numpy.savetxt('a.txt',a,fmt='%.3f')

when I open the txt file it looks like:

1.0002.0003.000

but when I paste it in word it looks like:

1.000

2.000

3.000

The problem is that another program reads the txt file as input line by line:

data = fid.readlines()

As a result it doesn't work correctly.How can I fix this problem?

mtrw
  • 32,117
  • 7
  • 59
  • 70
oops
  • 639
  • 3
  • 13
  • 19
  • What operating system are you using? – Joel Cornett Aug 01 '12 at 08:46
  • 3
    I'm not 100% sure on the details, but I do know that windows, mac os, and linux use different characters for their newlines. `\n` (carriage return) for unix/linux, `\r` (linefeed) for mac os, and `\n\r` in windows. Open up the file in python and do `print(repr(fid.read()))` and see if what type of newlines it contains. – Joel Cornett Aug 01 '12 at 08:50
  • 1
    Also see this [related question](http://stackoverflow.com/questions/4599936/handling-r-n-vs-n-newlines-in-python-on-mac-vs-windows) – Joel Cornett Aug 01 '12 at 08:51

1 Answers1

1

numpy.savetxt has a keyword argument newline which defaults to \n (the unix/linux line break).

You can either set it manually or use os.linesep to choose the newline character of your current operating system. So

import os
import numpy as np

a = np.array([1,2,3])
np.savetxt('a.txt', a, fmt='%.3f', newline=os.linesep)  

should be in one column with a windows editor and a program which runs under windows should be able to read it.

bmu
  • 33,069
  • 12
  • 87
  • 104