Python f.read 没有读取正确的字节数 [英] Python f.read not reading the correct number of bytes

查看:58
本文介绍了Python f.read 没有读取正确的字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码应该读取 4 个字节,但有时只能读取 3 个:

I have code that is supposed to read 4 bytes but it is only reading 3 sometimes:

f = open('test.sgy', 'r+')
f.seek(99716)
AAA = f.read(4)
BBB = f.read(4)
CCC = f.read(4)
print len(AAA)
print len(BBB)
print len(CCC)

exit()

这个程序返回:434

我做错了什么?谢谢!

推荐答案

您假设 read 做了一些它没有做的事情.正如其文档告诉您的那样:

You're assuming read does something it does not. As its documentation tells you:

read(...)
    read([size]) -> read at most size bytes, returned as a string.

它读取最多 size 个字节

如果您需要恰好 size 个字节,则必须创建一个包装函数.

If you need exactly size bytes, you'll have to create a wrapper function.

这是一个您可以改编的(未经过彻底测试的)示例:

Here's a (not thoroughly tested) example that you can adapt:

def read_exactly( fd, size ):
    data=""
    remaining= size
    while remaining>0:      #or simply "while remaining", if you'd like
        newdata= fd.read(remaining)
        if len(newdata)==0: #problem
            raise IOError("Failed to read enough data")
        data+=newdata
        remaining-= len(newdata)
    return data

<小时>

正如 Mark Dickinson 在评论中提到的,如果您使用的是 Windows,请确保您以二进制模式读取 - 否则您将面临读取(二进制)数据错误的风险.


As Mark Dickinson mentioned in the comments, if you're on Windows, make sure you're reading in binary mode - otherwise you risk reading your (binary) data wrong.

这篇关于Python f.read 没有读取正确的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆