【发布时间】:2019-02-27 11:38:33
【问题描述】:
我正在制作一个程序来检查文件中是否有任何用户的输入。如果用户输入当前不在文件中,那么我们会将该输入附加到 used_passwords 文件中,并要求用户再次输入其他内容。否则,如果他们重新输入我们刚刚添加的输入(或任何预设),那么我们想告诉他们他们不能重复使用密码。
这段代码遇到的问题是,每当我键入来自 used_passwords 文件中单词的字母,或者如果我在文件中键入单词的一部分时,程序就会告诉我不能重用密码。
例如:如果我输入“abc”,程序会告诉我我已经重用了该密码,我假设这可能是因为程序逐字符读取文件并读取 abcdeF 中的 abc!23 .
虽然,我不希望程序告诉我我不能重用文件中的一个或多个字符。我希望程序告诉我我不能重复使用程序中的一个词
我也想知道我们是否可以将输入或预设放入文件中的数组中。
fileUsed_Pass = open("used_passwords.txt", 'a')
fileUsed_Pass.write("\nabcdeF!23")
fileUsed_Pass.write("\n\n")
fileUsed_Pass.write("zxcbhK#44")
fileUsed_Pass.write("\n\n")
fileUsed_Pass.write("poiuyT&11")
fileUsed_Pass.write("\n\n")
fileUsed_Pass.close()
def password():
string = input("Enter Here:")
if string in open('used_passwords.txt').read():
print("You can not reuse that password!\n")
password()
else:
# file-append.py
f = open('used_passwords.txt','a')
f.write('\n'+string)
f.close()
password()
password()
更新:我已经让代码使用 with 语句工作。
我没有使用 If 和 else 语句,而是使用了 with 语句。
我正在做的是检查每一行,看看它是否有任何与我的输入字符串匹配的文本。如果没有,那么我们将使 some_variable 等于 True。如果不是,那么我们将使其等于 false。
with open("used_passwords.txt", 'r') as tFile:
for line in tFile:
if string != line and string+"\n" != line:
some_variable = True
else: #If it equals anything else from the file, then false
some_variable = False
break
#print(some_variable)
#this was added for me/the user to make sure that the with statement was working
之后,如果它等于 True:我们会将其添加到文件中。如果不是,我们会让用户输入另一个与文件中的任何密码都不匹配的密码。
tFile = open("used_passwords.txt", 'a')
if some_variable == True:
tFile.write("\n" + string)
print("\nGOOD! Password does not match old ones!")
elif some_variable == False:
print("\nYou can not re-use a password!")
password()
【问题讨论】:
标签: python string python-3.x file match