What's the type of read() function's return value?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-31 03:47:06

问题


I wanna read first 188 bytes from a binary file, and check whether the first character is 0x47. Code below:

import os
fp=open("try.ts","rb")
for i in range(100):
  buf=fp.read(188)
if buf[0]=="\x47":
  print "OK"
fp.close()

But it gives:

if buf[0]=="\x47":
IndexError: string index out of range

My questions are:

  1. What's the type of a return value in read() function?
  2. How can I get the first character in a string or array?

回答1:


if buf[0]=="\x47":
IndexError: string index out of range

That means your buf is empty. You overwrote it 100 times in your loop. The file probably doesn't have 18800 bytes in it. At the end of a file read just returns an empty string. Did you mean to put your if inside the for? If so, indent it accordingly.




回答2:


  1. What's the type of a return value in read() function?

You mean the method read of type file. The command help(file.read) gives:

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

If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.


  1. How can I get the first character in a string or array?

Just like you did, [0].



来源:https://stackoverflow.com/questions/16037390/whats-the-type-of-read-functions-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!