来自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);
答案 0 :(得分:2)
您需要从haystack
读取字符串,而不仅仅是needle
。类似的东西:
haystack= open("haystack.wav",'r').read()
或
with open("haystack.wav",'r') as inf:
haystack = inf.read()