gpt4 book ai didi

python - read() 函数的返回值是什么类型?

转载 作者:太空宇宙 更新时间:2023-11-04 06:52:55 26 4
gpt4 key购买 nike

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

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. read() 函数的返回值类型是什么?
  2. 如何获取字符串或数组中的第一个字符?

最佳答案

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

这意味着您的 buf 是空的。您在循环中将其覆盖了 100 次。该文件可能没有 18800 字节。在文件的末尾 read 只返回一个空字符串。您是想将 if 放在 for 中吗?如果是这样,相应地缩进它。

关于python - read() 函数的返回值是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16037390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com