Python实现文件中密码精确匹配的问题求助
密码精确匹配问题解决
需求:编写Python程序,检查输入密码是否存在于passwords.txt文件中,要求仅精确匹配完整密码(文件内每个密码单独占一行),不能匹配密码的部分片段。
当前问题:
- 用
in运算符会误匹配子串,比如输入密码的一部分也会返回True - 改用
==或readline()/readlines()方法时,明明密码存在却返回False
现有代码:
FILENAME = 'passwords.txt' password = input('Enter your own password: ').replace(' ', '') def check(): with open(FILENAME, 'r') as myfile: content = myfile.read() return password in content ans = check() if ans: print(f'Password is recorded - {ans}') else: print(f'Password is not recorded - {ans}')
问题原因
- 用
read()读取整个文件成字符串后,password in content会检查子串,自然会匹配到密码片段 - 用
readlines()读取时,每行末尾会保留换行符\n,比如文件里的123会被读成123\n,和输入的123用==比较时不相等,导致返回False
修正方案
方案1:逐行读取并去除换行符
遍历文件的每一行,用strip()去掉换行符和前后空白,再和输入密码精确比较:
FILENAME = 'passwords.txt' password = input('请输入密码:').replace(' ', '') def check(): with open(FILENAME, 'r') as myfile: for line in myfile: # 去除换行符和前后空白,避免因格式问题匹配失败 if line.strip() == password: return True return False ans = check() if ans: print(f'密码已记录 - {ans}') else: print(f'密码未记录 - {ans}')
方案2:将所有密码存入集合(适合大文件,查询更快)
把文件里的所有密码处理后存入集合,利用集合的O(1)查询效率:
FILENAME = 'passwords.txt' password = input('请输入密码:').replace(' ', '') def check(): with open(FILENAME, 'r') as myfile: # 生成集合时自动去除每行的换行符和空白 passwords = {line.strip() for line in myfile} return password in passwords ans = check() if ans: print(f'密码已记录 - {ans}') else: print(f'密码未记录 - {ans}')
注意事项
- 如果密码本身包含前后空白,不要用
strip(),改用rstrip('\n')只去掉换行符,避免修改密码内容 - 输入处理时的
replace(' ', '')是去掉输入中的空格,如果密码允许包含空格,需要删除这行
内容的提问来源于stack exchange,提问作者user19191583
相关产品推荐
相关产品推荐

