1

I faced a problem with writing structured array in txt file. Having an output file (outfile) opened, I use the following numpy function:

np.savetxt(*outfile*, ***recarray***, fmt=['%s','%-7.4f','%-7.4f','%-7.4f'])

The recarray is like [ (b'H', 0.9425, 0.1412, 7.1414) ... (b'N', 1.0037, 4.0524, 6.8000) ], where the first element has numpy.bytes_ type and others are numpy.float64.

An error message appears while writing this recarray in file:

TypeError: must be str, not bytes

So, what is the easiest way to put this array in file? Maybe there is another function?

1 Answer 1

1

I assume that you are using Python 3.0. In this case, you have to specify before '%s' the letter b like this : b'%s'

In Python3, the default string type is unicode, so you have use the extra b to mark byte strings.

Your script should be :

np.savetxt(*outfile*, ***recarray***, fmt=[b'%s','%-7.4f','%-7.4f','%-7.4f'])

Don't forget to write wb when you are opening your .txt file :

file = open('workfile.txt','wb')
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! It works now. But now there is another question. Is it possible to turn b'H' just to single H symbol? And also I don't understand why even setting delimiter='\n' it doesn't write the elements of recarray in file like this, i.e. single element in one line: H 0.9425 0.1412 7.1414 ... N 1.0037 4.0524 6.8000 but all of them are written in line. The same problem with header, which is also printed in line.
If the first problem is solved, please set my answer as solution to the others users. You should open a new question because your second one is kind different to the first one.
dear @Andromedae93, thank you again for your help. I prepared a separate question just as you suggested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.