Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending array rows to .txt file in Python 3

I am simply trying to put my 11-column, single row of values into a text file that I can append new rows to. I am used to python 2.7 and I do not understand why my np.savetxt is not behaving the same as previously.

I know that this will create my text file without having any type errors:

with open("testtext.txt", "wb") as myfile:
    np.savetxt(myfile, mydata, fmt="%.5f", delimiter=' ', newline=' ')

However when I then run my code to receive my new data that I need to append, and I change it to:

with open("testtext.txt", "ab") as myfile:
    np.savetxt(myfile, mynewdata, fmt="%.5f", delimiter=' ', newline=' ')

It does not put mynewdata into a new row. I have input \n into newline, I have tried " " instead of ' ', I have tried \r\n but that was a longshot.. Please help, I feel like this should be a simple thing. Thank you.

like image 397
layces Avatar asked Oct 18 '25 18:10

layces


1 Answers

Going through your question again, so, if your new array(row) not started in a new row, that should be the last line of your text file was not ended with newline. So as @hpaulj pointed out, this should work:

with open("testtext.txt", "wb") as myfile:
    f.write(b'\n')
    ...

If you are running on windows, take '\r\n' instead of '\n'.

like image 191
Will Avatar answered Oct 20 '25 07:10

Will



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!