Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14040

Reading a structured binary file with numpy: fromfile vs. read & frombuffer

$
0
0

I’m reading a binary file using numpy and wondering whether I should use repeated calls to numpy.fromfile or reading from the file manually and calling numpy.frombuffer:

# Alternative 1: fromfilewith open(path, 'rb') as f:    num = numpy.fromfile(f, 'u4', 1)[0]    l = numpy.fromfile(f, 'u4', num)    o = numpy.fromfile(f, 'u4', num)    m = numpy.fromfile(f, 'f4', num)    c = numpy.fromfile(f, '3f4', num)    s = numpy.fromfile(f, '3u4', num)# Alternative 2: read & frombufferdef fread(f, fmt):    dtype = numpy.dtype(fmt)    return numpy.frombuffer(f.read(dtype.itemsize), dtype)[0]with open(path, 'rb') as f:    num = fread(f, 'u4')    l = fread(f, f'({num},)u4')    o = fread(f, f'({num},)u4')    m = fread(f, f'({num},)f4')    c = fread(f, f'({num},3)f4')    s = fread(f, f'({num},3)u4')

Is there a difference (performance or otherwise) between these two methods?


Viewing all articles
Browse latest Browse all 14040

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>