无法搜索 python 中的文件

Can't search files in python

代码

f = open("C:\Users\Administrator\OneDrive\Documents\CS project 12th\Command.txt", "r")
g = open("C:\Users\Administrator\OneDrive\Documents\CS project 12th\Reply.txt","r")
list1 = f.readlines()
list2 = g.readlines()
st = 'hello'
index = 0
for i in f:
    if st in i:
        print("Found it")
    else:
        print("Not found")

所以这应该做的是在文件 f

中搜索一个字符串

The file F

但它 returns 一个空白输出。

发生这种情况的任何原因。

这是因为您使用了 readlines,从文件中取出行,而不是尝试:

for i in list1:
    if st in i:
        print("Found it")
    else:
        print("Not found")

我找到了答案,因为我使用的是 readlines,它使光标位于末尾,搜索没有返回任何结果。 简而言之,解决方法是删除 readline、read 或任何 i/o 阅读命令。