所以基本上我正在用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
在此nicknames.txt仅在每行中包含一个昵称列表,文件中包含5个昵称。
答案 0 :(得分:0)
如果要在给定昵称存在于该文件中时执行某些操作:
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
您可以在此问题上实现许多目标。我相信这两个可以完成。