检查昵称时如何检查数组中的每个元素

2024-09-19 23:41:16 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上我在python上写一个程序,我需要的一个子例程是没有重复的昵称,所以我做的是把所有的昵称添加到一个txt文件中,然后我想读取这个文件,确保昵称和文件中的昵称不一样。代码如下:

sAskNick = input ("What nickname would you like to proceed with?: ")

nicknames = open("nicknames.txt","a+")
aAllNicks = []

with open ("nicknames.txt") as f:
aAllNicks = f.read().splitlines()

for i in range(0,4):
    while sAskNick == aAllNicks[i]:
        print("Nickname used/inappropriate")

    else:
        print("Valid nickname")
        break

在这个昵称.txt文件中,每行只包含一个昵称列表,文件中有5个昵称


Tags: 文件代码程序txtinputwithnicknameopen
1条回答
网友
1楼 · 发布于 2024-09-19 23:41:16

如果要在给定昵称位于该文件中时执行操作:

given_nickname = input('What is your nickname?')

#Read the file:
nicknames = open(r'c:\filelocation','r').read().splitlines()

for element in range(len(nicknames)):
    if given_nickname in nicknames:
        print('{0} is in the nicknames list'.format(given_nickname))
    else:
        print('{0} is NOT in the list'.format(given_nickname))

如果每次输入昵称时都要编辑文本文件,可以使用以下方法进行编辑。 注意: 当然,如果您在每行中使用干净的文本文件保留每个昵称,这种情况也会起作用:

#Read the file:
file_location = r'somepath'
read_file = open(file_location,'r').read().splitlines()
nicknames = list(read_file) #catch the file as a list, its an optional line for cleaner code

def edit_file(nickname,file_location):
    f = open(file_location,'a').write('\n{0}'.format(nickname)) # before adding each nickname,start a new line in the text file



while True:
    given_nickname = input('What is your nickname?')
    if given_nickname not in nicknames:
        print('Welcome {0}!'.format(given_nickname))
        edit_file(nickname = given_nickname,file_location = file_location)
        break # stop the execution

    else:
        print('Error! {0} already chosen!'.format(given_nickname))
        #looping over the while loop if nickname is taken


在这个问题上你可以达成很多目标。我相信这两个人中的一个能完成

相关问题 更多 >