3

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?

3
  • What operating system are you using? Commented Aug 1, 2012 at 8: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. Commented Aug 1, 2012 at 8:50
  • 1
    Also see this related question Commented Aug 1, 2012 at 8:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Also, some better text editors (Geany, Notepad++, etc.) can handle this issue automatically in Windows.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.