R readBin与Python结构

Mar*_* P. 6 python r binaryfiles

我试图使用Python读取二进制文件.其他人使用以下代码使用R读取数据:

x <- readBin(webpage, numeric(), n=6e8, size = 4, endian = "little")
      myPoints <- data.frame("tmax" = x[1:(length(x)/4)],
                             "nmax" = x[(length(x)/4 + 1):(2*(length(x)/4))],
                             "tmin" = x[(2*length(x)/4 + 1):(3*(length(x)/4))],
                             "nmin" = x[(3*length(x)/4 + 1):(length(x))])
Run Code Online (Sandbox Code Playgroud)

使用Python,我正在尝试以下代码:

import struct

with open('file','rb') as f:
    val = f.read(16)
    while val != '':
        print(struct.unpack('4f', val))
        val = f.read(16) 
Run Code Online (Sandbox Code Playgroud)

我的结果略有不同.例如,R中的第一行返回4列为-999.9,0,-999.0,0.对于所有四列(下图),Python返回-999.0.

Python输出: 在此输入图像描述

R输出: 在此输入图像描述

我知道他们正在使用一些[]代码来填充文件的长度,但是我不知道在Python中究竟是如何做到这一点的,我也不明白为什么他们这样做.基本上,我想重新创建R在Python中所做的事情.

如果需要,我可以提供更多代码库.我不想用不必要的代码来压倒.

Hko*_*oof 0

这是一种不那么消耗内存的方法来完成同样的事情。它可能也快一点。(但这对我来说很难检查)

我的计算机没有足够的内存来运行包含这些大文件的第一个程序。这个确实可以,但我仍然需要先创建一个仅包含 tmax 的列表(文件的前 1/4),然后打印它,然后删除该列表,以便为 nmax、tmin 和 nmin 有足够的内存。

但这也说 2018 年文件中的 nmin 都是 -999.0。如果这没有意义,你能检查一下 R 代码是做什么的吗?我怀疑这就是文件中的内容。当然,另一种可能性是我完全错了(我对此表示怀疑)。然而,我也尝试了2017年的文件,那个文件没有这样的问题:所有 tmax, nmax, tmin, nmin 都有大约 37% -999.0 的。

无论如何,这是第二个代码:

import os
import struct

# load_data()
#   data_store : object to append() data items (floats) to
#   num        : number of floats to read and store
#   datafile   : opened binary file object to read float data from
#
def load_data(data_store, num, datafile):
    for i in range(num):
        data = datafile.read(4)  # process one float (=4 bytes) at a time
        item = struct.unpack("<f", data)[0]  # '<' means little endian
        data_store.append(item) 

# save_list() saves a list of float's as strings to a file
#
def save_list(filename, datalist):
    output = open(filename, "wt")
    for item in datalist:
        output.write(str(item) + '\n')
    output.close()

#### MAIN ####

datafile = open('data.bin','rb')

# Get file size so we can calculate number of points without reading
# the (large) file entirely into memory.
#
file_info = os.stat(datafile.fileno())

# Calculate number of points, i.e. number of each tmax's, nmax's,
# tmin's, nmin's. A point is 4 floats of 4 bytes each, hence number
# of points = file-size / (4*4)
#
num = int(file_info.st_size / 16)

tmax_list = list()
load_data(tmax_list, num, datafile)
save_list("tmax.txt", tmax_list)
del tmax_list   # huge list, save memory

nmax_list = list()
load_data(nmax_list, num, datafile)
save_list("nmax.txt", nmax_list)
del nmax_list   # huge list, save memory

tmin_list = list()
load_data(tmin_list, num, datafile)
save_list("tmin.txt", tmin_list)
del tmin_list   # huge list, save memory

nmin_list = list()
load_data(nmin_list, num, datafile)
save_list("nmin.txt", nmin_list)
del nmin_list   # huge list, save memory
Run Code Online (Sandbox Code Playgroud)