简体   繁体   English

Python f.read没有读取正确的字节数

[英]Python f.read not reading the correct number of bytes

I have code that is supposed to read 4 bytes but it is only reading 3 sometimes: 我的代码应该读取4个字节但有时只读3个:

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()

And this program returns: 4 3 4 并且该程序返回:4 3 4

What am I doing wrong? 我究竟做错了什么? Thanks! 谢谢!

You're assuming read does something it does not. 你假设read做了它不做的事情。 As its documentation tells you: 正如其文档告诉您:

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

it reads at most size bytes 最多读取size字节

If you need exactly size bytes, you'll have to create a wrapper function. 如果您需要精确的 size字节,则必须创建包装函数。


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

As Mark Dickinson mentioned in the comments, if you're on Windows, make sure you're reading in binary mode - otherwise you risk read ing your (binary) data wrong. 正如Mark Dickinson在评论中提到的,如果您使用的是Windows,请确保您正在以二进制模式阅读 - 否则您可能会错误地read (二进制)数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM