reading float from binary data file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cesco

    #1

    reading float from binary data file

    Hi,

    I have a binary file containing 1000 floating point numbers. I want to
    load that file into an array. A way to do it could be the following:
    [color=blue][color=green][color=darkred]
    >>> import array
    >>> data = array.array('f' )
    >>> f = open('FileName. bin', 'rb')
    >>> data.fromfile(f , 1000)[/color][/color][/color]

    Now I have the following problem: if I don't know how many values the
    file contains and I want to read all the values till the last one what
    shall I do?

    Thanks & regards
    Francesco

  • Diez B. Roggisch

    #2
    Re: reading float from binary data file

    cesco schrieb:[color=blue]
    > Hi,
    >
    > I have a binary file containing 1000 floating point numbers. I want to
    > load that file into an array. A way to do it could be the following:
    >[color=green][color=darkred]
    >>>> import array
    >>>> data = array.array('f' )
    >>>> f = open('FileName. bin', 'rb')
    >>>> data.fromfile(f , 1000)[/color][/color]
    >
    > Now I have the following problem: if I don't know how many values the
    > file contains and I want to read all the values till the last one what
    > shall I do?[/color]

    Divide the length of the file by the size of one float and use that as
    argument to fromfile.

    Diez

    Comment

    • Peter Hansen

      #3
      Re: reading float from binary data file

      cesco wrote:[color=blue]
      > I have a binary file containing 1000 floating point numbers. I want to
      > load that file into an array. A way to do it could be the following:
      >[color=green][color=darkred]
      >>>>import array
      >>>>data = array.array('f' )
      >>>>f = open('FileName. bin', 'rb')
      >>>>data.fromfi le(f, 1000)[/color][/color]
      >
      > Now I have the following problem: if I don't know how many values the
      > file contains and I want to read all the values till the last one what
      > shall I do?[/color]

      Maybe RTFM, and then wrap the .fromfile() call with an appropriate
      exception handler:

      '''
      fromfile(f, n)
      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.
      '''

      Note the last sentence above.

      -Peter

      Comment

      Working...