简体   繁体   中英

How do I switch been text and binary write mode in Python 3?

I recently switched to Python 3. In my code I had a numpy save as text command

f_handle = open('results.log','a')
f_handle.write('Some text')
numpy.savetxt(f_handle, X, delimiter=',', fmt='%.4f') 

In Python 3 this causes an error for the numpy command, the flag needs to be 'ab', that is, writing in binary. Now I mix several write statements after each other so in order to call the Numpy command I would have to do something like this,

f_handle = open('results.log','a')
f_handle.write('Some text...')
f_handle.close()

f_handle = open('results.log','ab')
numpy.savetxt(f_handle, X, delimiter=',', fmt='%.4f') 
f_handle.close()

f_handle = open('results.log','a')
f_handle.write('Some more text...')

This seems like a very ineffective way of doing things especially if you write many things. So how should I do it?

You can just encode text before write:

with open('results.log','ab') as f_handle:
    f_handle.write('Some text...'.encode('utf-8'))

You can create a binary string with the b flag.

In [101]: with open('test.txt','wb') as f:
   .....:     f.write(b'some binary string text\n')

I use that when creating test strings from genfromtxt (which also insists on working with byte files.

In [103]: txt=b'''1,2,3
   .....: 4,5,6'''.splitlines()

In [104]: np.genfromtxt(txt,delimiter=',')
Out[104]: 
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

genfromtxt often uses asbytes :

In [109]: np.lib.npyio.asbytes??
Type:        function
String form: <function asbytes at 0xb5a74194>
File:        /usr/lib/python3/dist-packages/numpy/compat/py3k.py
Definition:  np.lib.npyio.asbytes(s)
Source:
    def asbytes(s):
        if isinstance(s, bytes):
            return s
        return str(s).encode('latin1')

np.savetxt also uses it to write the comments and each row of your array:

fh.write(asbytes(comments + header + newline))
fh.write(asbytes(format % tuple(row2) + newline))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM