将readBin R转换为Python

时间:2018-03-15 10:30:49

标签: python r

我尝试使用readBin函数(R)将一些代码转换为Python。

R代码:

datFile = file("https://stats.idre.ucla.edu/stat/r/faq/bintest.dat", "rb")
i<-readBin(datFile, integer(), n = 4, size=8, endian = "little", signed=FALSE)
print(i)

返回:

[1] 1 3 5 7

我在Python中的尝试:

with open("bintest.dat", "rb") as datfile:
    i = int.from_bytes(datfile.read(8), byteorder='little', signed=False)
    print(i)

返回:

8589934593

如何在Python中获得相同的输出(我知道我缺少n参数,但我找不到正确实现它的方法)。

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

with open("bintest.dat", "rb") as f:
    # this is exactly the same as 'n = 4' in R code
    n = 4
    count = 0
    byte = f.read(4)
    while count < n and byte != b"":
        i = int.from_bytes(byte, byteorder='little', signed=False)
        print(i)
        count += 1
        # this is analogue of 'size=8' in R code
        byte = f.read(4)
        byte = f.read(4)

或者您可以将其作为一项功能。目前没有使用某些参数,以后再使用:)

def readBin(file, fun, n, size, endian, signed):
    with open(file, "rb") as f:
        r = []
        count = 0
        byte = f.read(4)
        while count < n and byte != b"":
            i = int.from_bytes(byte, byteorder=endian, signed=signed)
            r.append(i)
            count += 1
            byte = f.read(4)
            byte = f.read(4)
    return r

然后这将是用法:

i = readBin('bintest.dat', int, n = 4, size = 8, endian = 'little', signed = False)
print(i)
[1, 3, 5, 7]

您可以查看一些链接:

Working with binary data

Reading binary file