检查是否已将某些内容输入文件?

时间:2017-01-20 16:38:40

标签: python python-3.x

所以我需要这个来检查他们想要的用户名是否已经被采用但是我认为它不是最有效的方式而且它打印出3" USERNAME TAKEN"想要知道最有效的方法来检查它是否已经在文本文件中,然后再次询问用户名。

z = "I"
while z == "I" :
    print ("What would you like your username to be?")
    username = input()
    u = open ("USERNAME.txt", 'r')
    for line in enumerate(u, 1):
        if username in line :
            u.close()
            z = "A"
            break
        else :
            print ("USERNAME TAKEN")
            z = "I"

2 个答案:

答案 0 :(得分:0)

z = "I"
while z == "I" :
    print ("What would you like your username to be?")
    username = raw_input()
    if username in open('example.txt').read():
        print "Username taken"
    else:
        print "Username available"
        z='A'

答案 1 :(得分:-1)

Shijo在这里有最紧凑的答案,但我认为值得提出使用一种方法来检查是否已经使用了用户名,因为检查它的代码可以在以后重用,并且它会使更大的程序更具可读性

def username_taken(username):
    u = open("USERNAME.txt", "r")
    if username in u.read().splitlines():
        return True
    else:
        return False

while True:
    print ("What would you like your username to be?")
    username = input()
    if username_taken(username) == True:
        print ("Username Taken, please choose again.")
    else:
        print ("Username is valid.")
        break