读取循环的文本文件会产生意外的输出

2024-04-19 03:12:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何阅读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

Tags: 文件代码txt示例forreadlineisdemo
2条回答
with open("demo.txt", "r") as f:
    for word in f:
        print(word)
        if "thanks" in word:
            print("found it")
            break

文件是可iterable的,所以如果你想逐行读取一个文本文件,你所要做的就是遍历它。另外,您必须确保文件在使用后关闭—这可以通过with语句轻松完成。最后,行以(依赖于系统的)换行标记结束,您可能需要将其剥离以进行比较。你知道吗

你的代码应该是这样的:

# nb: "r" (read) is the default
with open("path/to/your/file") as f:
    for line in f:
        # removes the ending newline marker 
        line = line.rstrip("\n") 
        print(line)
        # given your spec 'when it finds the word "thanks"'
        # I assume that it doesn't matter if there's
        # something else in the line, so we test for
        # containment.
        if "thanks" in line:
            print("found it")

相关问题 更多 >