如何检查文本文件中的一行文本?

How do you check for a line of text in text files?

我没有收到任何错误,但它似乎没有检查我的文件中的文本,因为它会附加您输入的任何内容。有人可以帮忙吗?

guest_name = input("What is your name: ")
with open("guests.txt", "a+") as guests_txt:

    names = guests_txt.readlines()


    def find_name():
        if guest_name.lower() in names:
            print("Your name is already taken.")
            name_taken = True
            return name_taken

    name_taken_function = find_name()

    if not name_taken_function:
        guests_txt.write(f"{guest_name.lower()}\n")

模式a+打开文件是追加的,所以打开的时候,当前位置在文件末尾。 readlines() returns 一个空列表。

你应该在阅读它之前guests_txt.seek(0)

它不起作用的原因是因为.readlines()方法没有去掉多余的'\n',所以用户输入的名字永远不会等于现有的那些。请改用 .read().splitlines()。另外,尝试打开文件两次,一次以读取模式,然后以追加模式:

guest_name = input("What is your name: ")

with open("guests.txt", "r") as guests_txt:
    name_taken = False
    names = guests_txt.read().splitlines()
    if guest_name.lower() in names:
        if guest_name.lower() in names:
            print("Your name is already taken.")
            name_taken = True

with open("guests.txt", "a") as guests_txt:
    if not name_taken:
        guests_txt.write(f"\n{guest_name.lower()}")

当您使用 a+ 打开文件时,位置设置为最后一个字符。当您尝试阅读它时,由于最后一个字符之后没有其他内容,您将得到一个空文本。

使用guests_txt.seek(0)查找到开头,然后阅读。
另一个问题是,.readlines() 不会删除 \n 字符。相反,您可以使用 .read().splitlines() 来获取没有换行符的行:

guest_name = input("What is your name: ")
with open("guests.txt", "a+") as guests_txt:

    guests_txt.seek(0)
    names = guests_txt.read().splitlines()

    def find_name():
        if guest_name.lower() in names:
            print("Your name is already taken.")
            name_taken = True
            return name_taken

    name_taken_function = find_name()

    if not name_taken_function:
        guests_txt.write(f"{guest_name.lower()}\n")

你可以比许多其他答案更简单地实现这一点。

guest_name = input("What is your name: ")
with open("guests.txt", "a+") as guest_txt:
    guest_txt.seek(0)
    names = guest_txt.read().splitlines()
    if guest_name.lower() in names:
        print(f"Sorry, {guest_name}, your name is already taken.")
    else:
        guest_txt.write(f"{guest_name.lower()}\n")
        print(f"Thanks, {guest_name}, your name has been recorded.")

要添加新名称,您可以使用 guests_file.seek(0, io.SEEK_END)。我还建议简化代码并改进名称:

guest_name = input("What is your name: ").lower()
with open("guests.txt", "a+") as guests_file:
    guests_file.seek(0)
    names = guests_file.readlines()

    def name_is_taken():
        if guest_name + '\n' in names:
            print("Your name is already taken.")
            return True

    if not name_is_taken():
        guests_file.write(f"{guest_name}\n")