3

I'm trying to write a 5x3 array to a text file following an example found here using this code.

import numpy as np
data = np.loadtxt('array_float.txt')
with open('out.txt', 'w') as outfile:
    for data_slice in data:
        np.savetxt(outfile, data_slice, fmt='%4.1f')

It results in the following error:

File C:\Python34\lib\site-packages\numpy\lib\npyio.py", line 1087, in savetxt
  fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes

It seems savetxt doesn't like the outfile object. I'm able to get savetxt to work when I specify the actual outfile name. For example, this works:

np.savetxt('out.txt', data_slice, fmt='%4.1f')

But only the last line of the array gets save to 'out.txt'.

2 Answers 2

3

You should open the file in binary mode (using ab or wb)

import numpy as np
data = np.loadtxt('array_float.txt')
with open('out.txt', 'ab') as outfile:
    for data_slice in data:
        np.savetxt(outfile, data_slice, fmt='%4.1f')
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that works but the array is all on one line in the output file. How do I get each line of the array to write to a new line in the output file?
@DaveLeighton Try np.savetxt(outfile, data_slice, fmt='%4.1f', newline="\n") instead
Yeah, that was the first thing I tried, but it didn't change the output. Still all on one line.
@RafaelCardoso: For portability to a Windows system with a file opened in binary mode, shouldn't that be something like newline=os.linesep? Windows text editors often treat \n by itself as plain whitespace or nothing, and only \r\n actually gets rendered as a line break. The default is already \n after all, so newline="\n" doesn't change behavior.
1

I suggest you use Python's pickle module. It allows the saving of any array with very few complications or lines of code.

Try this:

import pickle
f = open(name_of_file,'w')
pickle.dump(f,name_of_array)
f.close()

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.