Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查文件中是否已经输入了内容?_Python_Python 3.x - Fatal编程技术网

Python 检查文件中是否已经输入了内容?

Python 检查文件中是否已经输入了内容?,python,python-3.x,Python,Python 3.x,所以我需要这个来检查他们想要的用户名是否已经被使用,但我不认为这是最有效的方法,它会打印出3个“用户名被使用”,我想知道最有效的方法来检查它是否已经在文本文件中,然后是否再次要求使用用户名 z = "I" while z == "I" : print ("What would you like your username to be?") username = input() u = open ("USERNAME.txt", 'r') for line in e

所以我需要这个来检查他们想要的用户名是否已经被使用,但我不认为这是最有效的方法,它会打印出3个“用户名被使用”,我想知道最有效的方法来检查它是否已经在文本文件中,然后是否再次要求使用用户名

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"

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

请更新您的问题,添加您需要帮助的内容。你想知道如何检查名字是否被取了吗?或者您想了解如何分配用户名?或者您想检查文件中是否已经存在字符串?@VikashSingh donethankyou这工作非常完美,而且非常明显。注意,这可以简化为
z=True
,而z:
z=False
,而不是比较字母:P
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