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

时间:2017-11-01 04:10:17

标签: python string file testing

我正在尝试创建一个用户名数据库,代码全部运行我想要的,除了当我尝试测试文件是否包含输入的文本。由于某种原因,它只是运行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:

1 个答案:

答案 0 :(得分:2)

您只能拨打file.read一次 - 之后已经阅读过。

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