read()函数的返回值是什么类型? [英] What's the type of read() function's return value?

查看:99
本文介绍了read()函数的返回值是什么类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从二进制文件中读取前188个字节,并检查第一个字符是否为 0x47 。下面的代码:

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

但是它给出了:

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

我的问题是:


  1. <中的返回值的类型是什么code> read()函数?

  2. 如何获取字符串或数组中的第一个字符?

  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?


推荐答案

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

这意味着您的 buf 为空。您在循环中重写了100次。该文件中可能没有18800字节。文件 read 的末尾仅返回一个空字符串。您是要把 if 放入 for 中吗?如果是这样,则相应地缩进。

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.

这篇关于read()函数的返回值是什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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