Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3-numpy: Appending to a file using numpy savetxt

I am trying to append data to a file using numpy's savetxt function. Below is the minimum working example

#!/usr/bin/env python3 import numpy as np f=open('asd.dat','a') for iind in range(4):     a=np.random.rand(10,10)     np.savetxt(f,a) f.close() 

The error that I got is something about the type of the error

File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 1073, in savetxt fh.write(asbytes(format % tuple(row) + newline)) TypeError: must be str, not bytes

This error doesn't occur in python2 so I am wondering what the issue could be. Can anyone help me out?

like image 705
Meenakshi Avatar asked Jan 05 '15 19:01

Meenakshi


People also ask

Does NumPy Savetxt append?

The NumPy module savetxt() method is used to append the Numpy array at the end of the existing csv file with a single format pattern fmt = %s.

How do I write a NumPy array to a file in python?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

What is FMT in Savetxt?

fmtstr or sequence of strs, optional. A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d – %10.5f', in which case delimiter is ignored. For complex X, the legal options for fmt are: a single specifier, fmt='%. 4e', resulting in numbers formatted like ' (%s+%sj)' % (fmt, fmt)


1 Answers

You should open file by binary mode.

#!/usr/bin/env python3 import numpy as np         f=open('asd.dat','ab') for iind in range(4):     a=np.random.rand(10,10)     np.savetxt(f,a) f.close() 

reference: python - How to write a numpy array to a csv file? - Stack Overflow How to write a numpy array to a csv file?

like image 181
user4352571 Avatar answered Sep 21 '22 15:09

user4352571