返回索引位置

时间:2013-02-28 17:27:35

标签: python python-3.x

来自PHP背景,我正在学习如何使用Python。

如果在haystack needle中找到内容,我正在尝试返回索引位置

haystack= open("haystack.wav",'r')
needle = open("needle.wav",'r')
nedOffset = needle.read()[:46]

print(haystack.index(nedOffset))

它似乎不起作用,我收到错误:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print(haystack.index(ned[:46]))
AttributeError: '_io.TextIOWrapper' object has no attribute 'index'

如何解决?

在PHP中我会这样做:

$needle = file_get_contents("needle.wav", false, null, 46);
$haystack = file_get_contents("heystack.wav");
echo strpos($haystack,$needle);

1 个答案:

答案 0 :(得分:2)

您需要从haystack读取字符串,而不仅仅是needle。类似的东西:

haystack= open("haystack.wav",'r').read()

with open("haystack.wav",'r') as inf:
    haystack = inf.read()
相关问题