Python - 如何通过文本文件读取关键字

时间:2017-11-30 10:23:07

标签: python

**这是一个练习应用

我有一个包含id&的文本文件密码每对都在不同的行上,如下所示:

P1 dogs
P2 tree

然后我有2个功能允许用户添加另一个id /密码或通过选择ID然后选择新密码来更新密码。 (我已经删除了保存功能,因此在测试时我不会创建大量的对)

问题是如何编写检查功能,以便在用户创建新对时...它检查id /密码是否已存在。然后在更新密码功能上,它只检查密码是否存在?

到目前为止我的代码:

#Keyword check
def used_before_check(keyword, fname):
    for line in open(fname, 'r'):
        login_info = line.split()
        username_found = False
        for line in login_info:
            if keyword in line:
                username_found == True

            if username_found == True:
                return True
            else:
                return False

# New password function
def new_password():
    print("\nCreate a new password")
    new_id_input = input("Please give your new password an ID: ")
    new_password_input = input("Please enter your new password: ")

    print("ID in use?", used_before_check(new_id_input, txt_file))
    print("Password in use?", used_before_check(new_password_input, txt_file))

#Change password function
def change_password():
    print("\nChange password")
    id_input = input("Enter the ID of the password you'd like to change: ")
    password_input = input("Now enter the new password: ")

    print("password_input",used_before_check(password_input, txt_file))

3 个答案:

答案 0 :(得分:1)

创建一个函数将您的用户名/密码存储在字典中,然后您可以轻松地检查它是否有现有的用户名/密码

存储在字典中:

def process_file(fname):

    username_pw_dict = {}

    for line in open(fname, 'r'):
        login_info = line.rstrip().split()

        username = login_info[0]
        pw = login_info[1]
        username_pw_dict[username] = pw
    return username_pw_dict

username_pw_dict = process_file(fname)

然后您可以检查现有的用户名或密码,如下所示:

if new_username in username_pw_dict:
    print("username already exists")

if new_pw in username_pw_dict.values():
    print("password already exists")    

答案 1 :(得分:1)

最简单的方法是使用JSON:

import json
import os

def new_password(user, password, password_dict={}):
    if user in password_dict:
        password_dict[user] = password # change password
    else:
        password_dict[user] = password # new password
    return password_dict

def read_passwords(filename):
    if not os._exists(filename):
        return {}
    with open(filename, 'r') as f:
        s = f.read()
    return json.loads(s)

password_filename = 'my_passwords.json'
password_dict = read_passwords(password_filename)
user = ''
while not user == 'q':
    user = input('user:')
    password = input('new password:')
    if user != 'q':
        password_dict = new_password(user, password, password_dict)

s = json.dumps(password_dict)
with open(password_filename, 'w') as f:
    f.write(s)

并非我在new_password中包含了一个看似不必要的if子句。这只是为了您,您可以轻松地输入您自己的代码,在每种情况下您想要做什么(可能不同)。

答案 2 :(得分:1)

当您阅读文件时,请创建一个包含所有ID作为其键的字典。 在下一步中,反转字典键值对,使其所有值(即所有密码)成为其键。

最后,当您输入新的ID和密码时,只需检查这些词典以了解它们是否已存在。您可以参考以下代码:

dict_ids = {1 : "one", 2:"two", 3:"three"};


dict_pwds = {}
for key, value in dict_ids.items():
    for string in value:           
        dict_pwds[value] = key;


print "dict_ids ", dict_ids;
print "dict_pwds ", dict_pwds;


if 'myid' in dict_ids.keys():
  print "ID exist! "
else:
  print "New ID"

if 'mypwd' in dict_pwds.keys():
  print "Password exist! "
else:
  print "New Password"