将struct.unpack用法从python 2转换为3

时间:2018-03-25 01:21:15

标签: python python-3.x python-2.7

我有一些旧的py2代码,我用来打开一个二进制文件,然后读取+修改一堆数据。我现在用py3脚本调用它,我一直试图转换它,但是我被卡住了。有这条线:

tmp = list(struct.unpack("f" * size, f.read(4 * size)))

其中f = open(filename, 'rb')size始终为200.当我运行它时,我得到struct.error: unpack requires a bytes object of length 800。我做了f.read(4 * size)的打印,它只给了我b'',显然不是800个字符,那问题是什么?

这里是上下文的完整代码:

def getVectorData(filename):
    f = open(filename,"rb")
    words = int(f.read(4)) # # of unique words
    size = int(f.read(4)) # # of dimensions
    vocab = [" "] * (words * max_w)
    M = []
    for b in range(0,words):
        a = 0
        while True:
            c = f.read(1) # reading each word character by character.
            #print(c) # this does return actual data, not just ''
            vocab[b * max_w + a] = c;
            if len(c) == 0 or c == ' ':
                break
            if (a < max_w) and vocab[b * max_w + a] != '\n':
                a += 1
        print(f.read(4 * size))
        tmp = list(struct.unpack("f"*size,f.read(4 * size)))

0 个答案:

没有答案