TheGarrett
TheGarrett

Reputation: 311

Python - how to read through text file for keyword

**This is a practice application

I have a text file containing a id & a password. Each pair is on separate lines like so:

P1 dogs
P2 tree

I then have 2 functions to allow the user the add another id/password or update the password by selecting an ID then the new password. (I have removed the save functionality so I don't create loads of pairs when testing)

The question is how would I write a check function so that when the user is creating a new pair.. it checks if the id/password already exists. Then on the update password function, it only checks if the password exists?

My code so far:

#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))

Upvotes: 0

Views: 84

Answers (3)

A.G.Progm.Enthusiast
A.G.Progm.Enthusiast

Reputation: 982

When you are reading the file, make a dictionary with all the IDs as its keys. In next step, reverse the dictionary key-value pair so all its values (i.e all passwords) become its keys.

Finally, when you enter a new ID and password, just check those dictionaries to know if they already exist. You may refer to this below code:

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"

Upvotes: 1

mrCarnivore
mrCarnivore

Reputation: 5068

The easiest way would be to use 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)

Not that I have included a seemingly unnecessary if clause in new_password. This is just for you that you can easily enter your own code what you want to do (maybe different) in each case.

Upvotes: 1

kujosHeist
kujosHeist

Reputation: 854

Create a function to store your usernames/passwords in a dictionary, then you can easily check it for existing usernames/passwords

To store in dictionary:

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)

Then you can check for existing usernames or passwords like this:

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

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

Upvotes: 1

Related Questions