【问题标题】:Python, How to write a 2-d array to a binary File with precision (uint8, uint16)?Python,如何以精度(uint8,uint16)将二维数组写入二进制文件?
【发布时间】:2021-06-13 15:56:17
【问题描述】:

我希望有人可以向我解释如何将二进制输出写入文本文件。

我知道在 matlab 中,它非常简单,因为它有 'fwrite' 函数,格式如下:fwrite(fileID,A,precision)

但是,我不确定如何将其翻译成 python。我目前将数据存储在二维 numpy 数组中,并希望以与 matlab 相同的方式将其写入文件。

我尝试了以下方法:

#let Y be the numpy matrix
with open (filepath,'wb') as FileToWrite:
    np.array(Y.shape).tofile(FileToWrite)
    Y.T.tofile(FileToWrite)

但是,这并没有带来预期的结果。文件大小太大,数据格式不正确。 理想情况下,我应该能够将数据格式指定为 uint8 或 uint16。

任何帮助将不胜感激。

【问题讨论】:

  • 您可以使用savetxt,您可以在其中指定格式。

标签: python matlab binary


【解决方案1】:

所以,我想通了。解决方法如下。

#let Y be the numpy matrix
with open (filepath,'wb') as FileToWrite:
    np.asarray(Y, dtype=np.uint8).tofile(FileToWrite)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多