文件中还有多少未读字节?

3 投票
3 回答
8270 浏览
提问于 2025-04-17 04:10

我定期从一个文件中读取16位的帧,最后一帧我需要确认一下文件里是否有足够的数据,并且这个文件是否符合我的格式。

f.read(16)

如果没有更多的数据,它会返回一个空字符串;如果至少还有1个字节的数据,它就会返回这些数据。我该怎么检查文件里还有多少个未读的字节呢?

3 个回答

2

使用 seek(0, 2)tell()

BUFF = 16
f = open("someFile", "r")
x = 0
# move to end of file
f.seek(0, 2)

# get current position
eof = f.tell()  

# go back to start of file
f.seek(0, 0)

# some arbitrary loop
while x < 128:
    data = f.read(BUFF)
    x += len(data)

# print how many unread bytes left
unread = eof - x
print unread

文件对象 - Python库参考:

  • seek(offset[, whence]) 用来设置文件的当前位置,类似于标准输入输出的 fseek()。这里的 whence 参数是可选的,默认值是 0(表示绝对位置);其他值有 1(相对于当前的位置)和 2(相对于文件的末尾)。这个函数没有返回值。需要注意的是,如果文件是以追加模式打开的(模式 'a' 或 'a+'),那么任何 seek() 操作在下次写入时都会被撤销。如果文件只是以追加模式打开用于写入(模式 'a'),这个方法基本上是无效的,但对于以追加模式同时允许读取的文件(模式 'a+')来说,它仍然有用。如果文件是以文本模式打开的(没有 'b'),那么只有 tell() 返回的偏移量是合法的。使用其他偏移量会导致未定义的行为。并不是所有的文件对象都可以使用 seek()。

  • tell() 用来返回文件的当前位置,类似于标准输入输出的 ftell()。

3

可能会更容易使用一些..

def LengthOfFile(f):
    """ Get the length of the file for a regular file (not a device file)"""
    currentPos=f.tell()
    f.seek(0, 2)          # move to end of file
    length = f.tell()     # get current position
    f.seek(currentPos, 0) # go back to where we started
    return length

def BytesRemaining(f,f_len):
    """ Get number of bytes left to read, where f_len is the length of the file (probably from f_len=LengthOfFile(f) )"""
    currentPos=f.tell()
    return f_len-currentPos

def BytesRemainingAndSize(f):
    """ Get number of bytes left to read for a regular file (not a device file), returns a tuple of the bytes remaining and the total length of the file
        If your code is going to be doing this alot then use LengthOfFile and  BytesRemaining instead of this function
    """
    currentPos=f.tell()
    l=LengthOfFile(f)
    return l-currentPos,l


if __name__ == "__main__":
   f=open("aFile.data",'r')
   f_len=LengthOfFile(f)
   print "f_len=",f_len
   print "BytesRemaining=",BytesRemaining(f,f_len),"=",BytesRemainingAndSize(f)
   f.read(1000)
   print "BytesRemaining=",BytesRemaining(f,f_len),"=",BytesRemainingAndSize(f)
8

为了做到这一点,你需要知道文件的大小。使用 文件 对象,你可以这样做:

f.seek(0, 2)
file_size = f.tell()

变量 file_size 将会包含你文件的大小,单位是字节。在读取文件时,只需用 f.tell() - file_size 就可以得到剩余的字节数。所以:

撰写回答