我正在学习如何阅读txt文件并从中找到一些东西。下面的示例输出整个txt文件。我试图让它打印出“找到它”时,它发现了“谢谢”在txt文件。我错在哪里?你知道吗
这是我正在阅读的txt文件:
this is a
demo file
for exercises
thanks
bye
这是我写的代码:
f = open("demo.txt", "r")
print(f.readline())
print(f.readline())
for word in f:
print(word)
if word == "thanks":
print("found it")
这是输出:
this is a
demo file
for exercises
thanks
bye
Process finished with exit code 0
文件是可iterable的,所以如果你想逐行读取一个文本文件,你所要做的就是遍历它。另外,您必须确保文件在使用后关闭—这可以通过
with
语句轻松完成。最后,行以(依赖于系统的)换行标记结束,您可能需要将其剥离以进行比较。你知道吗你的代码应该是这样的:
相关问题 更多 >
编程相关推荐