[英]How do I switch been text and binary write mode in Python 3?
我最近切換到了Python3。在我的代碼中,我有一個numpy另存為文本命令
f_handle = open('results.log','a')
f_handle.write('Some text')
numpy.savetxt(f_handle, X, delimiter=',', fmt='%.4f')
在Python 3中,這會導致numpy命令出錯,該標志必須為“ ab”,即以二進制形式編寫。 現在,我依次混合使用多個write語句,以便調用Numpy命令,我必須執行類似的操作,
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...')
這似乎是一種非常無效的處理方式,尤其是當您編寫許多內容時。 那我該怎么辦呢?
您可以在寫入之前對文本進行編碼:
with open('results.log','ab') as f_handle:
f_handle.write('Some text...'.encode('utf-8'))
您可以使用b
標志創建一個二進制字符串。
In [101]: with open('test.txt','wb') as f:
.....: f.write(b'some binary string text\n')
當從genfromtxt
創建測試字符串時,我會用它(它也堅持使用字節文件。
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
通常使用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
也使用它來寫注釋和數組的每一行:
fh.write(asbytes(comments + header + newline))
fh.write(asbytes(format % tuple(row2) + newline))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.