Read/write raw file

Tweet


Python example to save the variable to raw file. numpy's tofile/fromfile function can write/read raw data. Raw file is useful when C++ wants to read the whole values inside the variable. By the way, if using only Python, it is better to use numpy file for reading/writing.

import numpy as np
a=np.array([
    [[0,1],[10,11],[20,21]],
    [[100,101],[110,111],[120,121]],
    [[200,201],[210,111],[220,221]],
    [[300,301],[310,311],[320,321]]
    ],dtype=np.float64)
print(a.dtype)
print(a.shape)
print(type(a))
print(a)
print()
a.astype(np.float32).tofile('a.raw')
b=np.fromfile("a.raw",dtype=np.float32).astype(np.float64).reshape(4,3,2)
print(b.dtype)
print(b.shape)
print(b)
print()
np.save("a.npy",a)
b=np.load("a.npy")
print(b.dtype)
print(b.shape)
print(b)
print()


Back