Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving numpy array to txt file as a single column?

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?

like image 992
oops Avatar asked Apr 06 '26 22:04

oops


1 Answers

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.

like image 150
bmu Avatar answered Apr 08 '26 12:04

bmu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!