我有一个函数我想用来检查一个字符串是否已包含在给定文件中。
该功能如下所示:
def check_dupe(filename, word):
print(filename)
print(word)
with open(filename, 'rb', 0) as file, mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(word.encode()) != -1:
print('dupe')
return True
我收到以下错误:
<_io.TextIOWrapper name='links' mode='r' encoding='ANSI_X3.4-1968'>
Traceback (most recent call last):
File "checker.py", line 277, in <module>
main()
File "checker.py", line 261, in main
text_links = [line.strip() for line in f if not check_dupe('completed_links', f)]
File "checker.py", line 261, in <listcomp>
text_links = [line.strip() for line in f if not check_dupe('completed_links', f)]
File "checker.py", line 240, in check_dupe
if s.find(word.encode()) != -1:
AttributeError: '_io.TextIOWrapper' object has no attribute 'encode'
如何防止这种情况发生?
答案 0 :(得分:0)
只需阅读stackstrace,从下到上:
<_io.TextIOWrapper name='links' mode='r' encoding='ANSI_X3.4-1968'>
Traceback (most recent call last):
File "checker.py", line 277, in <module>
main()
File "checker.py", line 261, in main
text_links = [line.strip() for line in f if not check_dupe('completed_links', f)]
File "checker.py", line 261, in <listcomp>
text_links = [line.strip() for line in f if not check_dupe('completed_links', f)]
File "checker.py", line 240, in check_dupe
if s.find(word.encode()) != -1:
AttributeError: '_io.TextIOWrapper' object has no attribute 'encode'
word
是_io.TextIOWrapper
,您尝试调用其不存在的encode()
方法。
word
是您传递到check_dupe()
函数的参数,第261行:
[line.strip() for line in f if not check_dupe('completed_links', f)]
您将f
作为word
的参数传递,f
是您从中读取行的文件。我想这是一个用open(“filename”)打开的文件,它返回_io.TextIOWrapper
我想你的意思是将line
作为参数传递,这确实是一个字符串:
[line.strip() for line in f if not check_dupe('completed_links', line)]