What is the equivalent of 'fread' from Matlab in Python?

后端 未结 4 1069
生来不讨喜
生来不讨喜 2020-12-14 21:35

I have practically no knowledge of Matlab, and need to translate some parsing routines into Python. They are for large files, that are themselves divided into \'blocks\', an

4条回答
  •  误落风尘
    2020-12-14 21:46

    From the documentation of fread, it is a function to read binary data. The second argument specifies the size of the output vector, the third one the size/type of the items read.

    In order to recreate this in Python, you can use the array module:

    f = open(...)
    import array
    a = array.array("L")  # L is the typecode for uint32
    a.fromfile(f, 3)
    

    This will read read three uint32 values from the file f, which are available in a afterwards. From the documentation of fromfile:

    Read n items (as machine values) from the file object f and append them to the end of the array. If less than n items are available, EOFError is raised, but the items that were available are still inserted into the array. f must be a real built-in file object; something else with a read() method won’t do.

    Arrays implement the sequence protocol and therefore support the same operations as lists, but you can also use the .tolist() method to create a normal list from the array.

提交回复
热议问题