(Python)如何测试文件中是否包含字符串

问题描述 投票:2回答:1

我正在尝试创建一个用户名数据库,代码全部运行我想要的,除了当我尝试测试文件是否包含输入的文本。由于某种原因,它只是运行elif语句并且如果文本中已经存在则命中else语句。

这是完整的代码:

class username:
    def add():
        while(True):
            file = open("usernames.txt", 'r+')
            names = list(file.read())
            entered = str(input("Username: "))
            if len(entered) == 0:
                print("Please enter a valid username\n")
                continue
            elif not(entered.isalpha):
                print("Please enter a valid username\n")
                continue
            elif entered in file.read():
                print("That name is already in use.",
                      "\nPlease enter a different username. \n")
                continue
            elif len(entered) < 4 or len(entered) > 12:
                print("Please enter a username with 4-12 characters.\n")
                continue
            else:
                print(entered)
                file.close()
                add = open("usernames.txt", 'a+')
                plusnewline = entered + "\n"
                add.write(plusnewline)
                add.close()
                break

    def list():
        file = open("usernames.txt","r+")
        names = file.read()
        print(names)
        file.close()

username.add()
username.list()

编辑:Shadow回答:

更改:

names = list(file.read())

至:

names = file.read()

并改变了:

elif entered in file.read():

至:

elif entered in names:
python string file testing
1个回答
2
投票

你只能打电话给file.read一次 - 之后它已经被阅读了。

使用file.seek(0)返回到文件的开头(这将允许您再次读取它),或者将内容缓存在变量中以便您可以重复使用它(即,参考您的names变量)

© www.soinside.com 2019 - 2024. All rights reserved.