I am using Python 3.5 64bit Windows OS. I am trying to write floating point values to a file. This is the code
with open('report.txt' , "ab") as f:
f.write(b"\n Result Pattern\n")
f.write('%f' %test_accuracy)
I have tried the new '{}'.format
specifier as well. However I get the following error
f.write('%f' %test_accuracy)
TypeError: a bytes-like object is required, not 'str'
So, how do I specify a format for writing digits , when the file mode is binary. Another point is that, I get an error if I try to write without the binary option.
Update:
I am aware of basic file writing in python and when to use b
. I have this snippet of numpy code where I am writing the array to the file as well.
np.savetxt(f , test_pat ,
header = 'A , B , C , D , E' ,
comments='' ,
delimiter = ',' ,
newline = '\r\n' ,
fmt = '%3d')
I get the aforementioned error at this point with error message as:
fh.write(asbytes(comments + header + newline))
TypeError: write() argument must be str, not bytes
It is then when I switch the mode to ab
strangely the error goes away.
Is the \r\n
a problem while trying to have it formatted nicely when opened through a notepad?
Another update:
Similar error and the answer suggest using binary
mode!
numpy savetxt append mode error