我最近切换到 Python 3。在我的代码中,我有一个 numpy 另存为文本命令
f_handle = open('results.log','a')
f_handle.write('Some text')
numpy.savetxt(f_handle, X, delimiter=',', fmt='%.4f')
在 Python 3 中,这会导致 numpy 命令出错,标志需要为“ab”,即以二进制形式写入。现在,我将多个写入语句混合在一起,因此为了调用 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'))
关于python - 如何在 Python 3 中切换文本和二进制写入模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467358/