【问题标题】:How do I switch been text and binary write mode in Python 3?如何在 Python 3 中切换文本和二进制写入模式?
【发布时间】:2016-05-26 17:21:36
【问题描述】:

我最近切换到 Python 3。在我的代码中,我有一个 numpy save as text 命令

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...')

这似乎是一种非常无效的做事方式,尤其是在您编写很多东西的情况下。那我该怎么做呢?

【问题讨论】:

    标签: python python-3.x numpy io


    【解决方案1】:

    您可以在写入之前对文本进行编码:

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

    【讨论】:

      【解决方案2】:

      您可以使用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 也使用它来编写 cmets 和数组的每一行:

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

      【讨论】:

        猜你喜欢
        • 2016-07-27
        • 1970-01-01
        • 2012-01-17
        • 2016-12-05
        • 2019-10-05
        • 2017-11-03
        • 2018-12-01
        • 1970-01-01
        • 2013-08-24
        相关资源
        最近更新 更多