How to save the data gathered in the address book? - python

I am using a file in text edit ubuntu. I am trying to figure out a way to save it. When I close the python shell and rerun it, it deletes all past info. Would I have to make a new function?
AdressBook = '/home/bookworm/AdressBook.txt'
contacts = {}
def write():
Data = open(AdressBook,'w')
for name, many in contacts.items():
Data.write(name + ',' + many)
Data.close()
def read():
Data = open(AdressBook, 'r')
stuff = Data.read()
print(stuff)
Data.close()
user = input('Would you like to acess your adress book?')
if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
It is only the deleted and added contacts to be saved
while user != 5:
user = input('''Select One:
Press 1 to update
Press 2 to display all contacts
Press 3 to search adress book
Press 4 to delete contacts
Press 5 to quit your adress book.''')
if user == '1':
name = input('Please enter the name of the contact that you would like to add.')
contact = input('Please enter the contact information of %s.'%name)
Name = '\n' + name
contacts.update( {Name : contact} )
print('')
print('%s was added to your adress book!' %name)
print('')
write()
elif user == '2':
read()
To call read function
elif user == '3':
name = input('What is the name of the person whose contacts you need?')
print(contacts[name])
To delete a contact
elif user == '4':
name = input('Type in the name of the contact that you would like to delete.')
del contacts[name]
print('Your contact List has sucessfully deleted %s' %name)
write()
elif user == '5':
print('Thank you for acessing your adress book!')
exit()
else:
exit()

Your file becomes empty everytime because you are taking contacts = {} in the start of the program. So instead of creating an empty dictionary, you need to initialize the dictionary with the file contents in the starting.
AdressBook = '/home/bookworm/AdressBook.txt'
contacts = initialize_contacts()
def write():
Data = open(AdressBook,'w')
for name, many in contacts.items():
Data.write(name + ',' + many + '\n')
Data.close()
def read():
Data = open(AdressBook, 'r')
stuff = Data.read()
print(stuff)
Data.close()
return stuff
def initialize_contacts():
data = read()
contact_list = data.split('\n')
for contact in contact_list[:-1]:
name,cont = contact.split(',')
contacts[name] = cont

Related

How to read and write on this file?

I have to write a code that does the following:
Create a menu with three options.
Print the subjects
Search for a subject
Q) Quit
Create a main() function
Prompt the user for a file name.
Prompt the user for an option from the menu.
Open the file and load the data into a list.
Option 1 should print all the school subjects in the list, under a title
Once all the records have been processed, print a count.
Option 2 should allow the user to search for a subject in the list.
Add exception handling. (add last)
Create your own text file, with a list of 10 or more school subjects.
Submit the program module(s) and the output.
For a bonus, create a second module and import it, or add a menu item to add names to the list and save the data to a new file.
I keep getting "file not found" and was wondering if anyone could help. I want to name the read file as subjects.txt
This is the code I have written:
#Display menu and ask for user to select option
def menu():
print('Enter "1" to print subjects')
print('Enter "2" to search subjects')
print('Enter "3" to add subject')
print('Enter "q" to quit')
option = input('Enter option: ')
return option.lower()
#Reading files
def read_subjects(file_name):
file1 = open(subjects, 'r')
return file1.readlines()
#Add new subjects
def write_to_file(file_name, subject):
current_lines = []
try:
current_lines = read_subjects(file_name)
except:
pass
current_lines.append(subject + '\n')
file1 = open(file_name, 'w')
file1.writelines(current_lines)
file1.close()
#Main function
def main():
correct_file_name = False
file_name = 'subjects'
subjects = []
# while loop to ensure a user selects an existing file with catch and try
while not correct_file_name:
file_name = input('Enter file name: ')
try:
subjects = read_subjects(subject)
correct_file_name = True
except:
print('Error file not found')
# while loop to implement contious flow of options
while True:
selected_option = menu()
# quit program
if selected_option == 'q':
quit()
# display subjects
if selected_option == '1':
print('Subjects')
# Strips the newline character
count = 0
for line in subjects:
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# search for a subject
if selected_option == '2':
subject = input('Search subject: ')
print('Subjects')
count = 0
for line in subjects:
striped_line = line.strip()
if subject.lower() in striped_line.lower() or striped_line.lower() in hobby.lower():
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# bonus add new hobbies
if selected_option == '3':
subject = input('Enter new hobby: ')
write_to_file('subjects.txt', subject)
# call main function
if __name__ == '__main__':
main()

how do we grab a specific information like the name from this?

I'm looking at this example and I want to figure out how can I search up a name instead of the ID, then display all the information for the name? For example if it has the ID of 1, name: Bob, department: sales, and job title: manager. If we search up "Bob", everything will display. Sorry this is long.
class Employee:
def __init__(self, name, ID, department, job_title):
self.__name = name
self.__ID = ID
self.__dept = department
self.__job = job_title
def set_name(self, name):
self.__name = name
def set_department(self, department):
self.__dept = department
def set_job_title(self, job_title):
self.__job = job_title
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID
def get_department(self):
return self.__dept
def get_job_title(self):
return self.__job
def __str__(self):
return 'Name: ' + self.__name + '\n' + \
'ID Number: ' + str(self.__ID) + '\n' + \
'Department: ' + self.__dept + '\n' + \
'Job Title: ' + self.__job
import pickle
def pickle_it(employees):
# Open file in binary write mode
output_file = open('employees.dat', 'wb')
# Write the data to the file
pickle.dump(employees, output_file)
# Close the file
output_file.close()
def unpickle_it():
try:
# Attempt to open file in binary read mode
input_file = open('employees.dat', 'rb')
except IOError:
# If the file doesn't exist, then create it by opening using write
# mode. Then just close and reopen in binary read mode.
file = open('employees.dat', 'wb')
file.close()
input_file = open('employees.dat', 'rb')
# Load the employees dictionary or create an empty dictionary if file is
# empty
try:
employees = pickle.load(input_file)
except:
employees = {}
# Close the file
input_file.close()
# Return the employees dictionary
return employees
import menu_choices
import save_load_dict
# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
employees = save_load_dict.unpickle_it()
choice = menu_choices.get_menu_choice()
while choice != QUIT:
if choice == LOOK_UP:
menu_choices.look_up(employees)
elif choice == ADD:
menu_choices.add(employees)
elif choice == CHANGE:
menu_choices.change(employees)
elif choice == DELETE:
menu_choices.delete(employees)
choice = menu_choices.get_menu_choice()
save_load_dict.pickle_it(employees)
main()
import employee_class
# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def get_menu_choice():
print('\n\033[4m' + 'Employee Directory' + '\033[0m')
print('1. Look up an employee')
print('2. Add a new employee')
print('3. Edit an employee\'s information')
print('4. Delete an employee')
print('5. Quit\n')
# Get the user's choice.
choice = int(input('Enter your choice: '))
# Validate the choice.
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
# return the user's choice.
return choice
# The look_up function looks up an employee and displays their information.
def look_up(employees):
# Get a name to look up.
ID = input('Enter an employee ID number: ')
# Look it up in the dictionary.
if ID in employees:
print(employees[ID])
else:
print('That ID number is not found.')
# The add function adds a new entry into the dictionary.
def add(employees):
# Get employee information.
name = input('Enter the employee\'s name: ')
ID = input('Enter the employee\'s ID number: ')
department = input('Enter the employee\'s department: ')
job_title = input('Enter the employee\'s job title: ')
# If the name does not exist, add it.
if ID not in employees:
employees[ID] = employee_class.Employee(name, ID, department, \
job_title)
else:
print('An entry with that ID number already exists.')
Your question heading asks for how to search using email while the class Employee has no email attribute.
To search using other attribute like Name:
Though the code snippets you pasted doesn't define what employees object is, it's a dict mapping between id and corresponding Employee object.
If you only need to search by name, you can make the employees dictionary as a mapping between Name and Employee objects (list, as multiple employee can have same name).
If you need a more dynamic solution that lets you search by just about anything, then you need to match with all attributes of each Employee object. And also will need to take care of case insensitivity in search.
def look_up(employees):
# Get any searchtext to lookup
searchtext = input('Enter search query to lookup')
matches = [emp for emp in employees.values()
if searchtext.lower() in [
emp.get_name().lower(),
emp.get_ID_number(), # Add .lower() if needed
emp.get_department().lower(), #.lower() for case insensitive match
emp.get_job_title().lower()
]
]
if not matches:
print(f'No employee matches any attribute for searchtext {searchtext}')
return None
# If there are valid matches
print(matches)
Eliminate any of the above fields if not needed.
You can go more crazier in terms of matching the string with partial matches like doing searchtext in candidate for candidate in [emp.<some_attributes>,..] or use levenshtein distance.
You'll need to take into account that two employees could have the same name. The following code (adapted from your existing look_up function) will return all the employees with the name specified, or a message that there are no employees with that name :
# The look_up function looks up an employee by name and displays their information.
def look_up_by_name(employees):
# Get a name to look up.
name = input('Enter an employee Name: ')
matches = [emp for emp in employees if emp['name'] == name]
if len(matches) == 0:
print('No employees with name "{}" found'.format(name))
else:
for m in matches:
print(m)

Compare login info to csv data and grant access

My program asks the user whether they have an account or not. If the user doesn't have an account, then the program creates a new account for the user and stores their details in a csv file. This part works fine. But if the user runs the program again (after account creation) and tries to log in with the same details (username, password), it doesn't work. How do I compare the login info to csv data and grant access?
##Two Subjects----> Computer Science and History
import csv
def main():
userAccount()
def userAccount():
print('-------------------------------')
userAccount = input('Do you already have an account: ')
if userAccount == 'No' or userAccount== 'N' or userAccount == 'no' or userAccount == 'n':
userSName = input('Name : ')
userSAge = input('Age : ')
userSYgroup = input('Year Group : ')
userGname = userSName[:3] + userSAge
print('Your username is : ',userGname.lower())
userSword = input('Password: ')
detail1 = [userSName,userSAge,userSYgroup,userGname,userSword]
with open('userData.csv','w',newline = '') as csvfile:
w = csv.writer(csvfile,delimiter = ',')
w.writerow(detail1)
elif userAccount == 'Yes' or userAccount == 'Y' or userAccount == 'yes' or userAccount == 'y':
userLName = input('Username: ')
passLWord = input('Password: ')
f = open('userData.csv','r',newline = '')
for i in f:
if userLName == f[0,3] and passLWord == f[0,4]:
print('Log In Successfull')
else:
print('Incorrect Username or Password')
main()
main()
Here's a fully working version with slight changes. Add it to your original code. Though it might break your current code, because I changed a few variables name. Rename them accordingly.
##Two Subjects----> Computer Science and History
import csv
def main():
userAccount()
print("rest of the code")
input() # keep window open
def userAccount():
print('-------------------------------')
# group possible inputs; no need for individual checks
noAccount = ["no", "NO", "n", "N"]
yesAccount = ["yes", "YES", "y", "Y"]
hasAccount = input('Do you already have an account: ')
if hasAccount in noAccount:
userName = input('Name : ')
userAge = input('Age : ')
userYear = input('Year Group : ')
userLogin = (userName[:3] + userAge).lower()
print('Your username is : ', userLogin)
userPW = input('Password: ')
details = [userName, userAge, userYear, userLogin, userPW]
# open file with 'a' instead of 'w' so multiple records can be added to csv
with open('userData.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(details)
# once the account is created, return to beginning
main()
elif hasAccount in yesAccount:
userLogin = input('Username: ')
userPW = input('Password: ')
granted = None
with open('userData.csv', 'r', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
# loop every row (record) in the csv file
for row in reader:
csvLogin = row[3]
csvPW = row[4]
if userLogin == csvLogin and userPW == csvPW:
granted = True
print('Log In Successfull')
# a user is matched; no need to check other records
break
# if input doesn't match any csv record, return to beginning
if granted is None:
print('Incorrect Username or Password')
main()
else:
# if user enters something other than yes/no, return to beginning
main()
main()

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))
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.
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")
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"

Why isn't my file writing method working?

import os
books = open(os.path.expanduser("~/Desktop/books.txt")).read()
b= books.split('\n')
del b[-1]
book={}
for i in b:
b1=i.split('\t')
book[b1[0]]=[b1[1],b1[2],b1[3]]
def all_book():
print "The Book List"
books = open(os.path.expanduser("~/Desktop/books.txt"))
print books.read()
def add_book():
print "Registering New Book"
books = open(os.path.expanduser("~/Desktop/books.txt"))
name = raw_input("Title: ")
author= raw_input("Author Name: ")
publisher =raw_input("Publisher: ")
n= int(b1[0])
n1 = n+1
newb= [str(n1), '\t', name, '\t', author,'\t', publisher]
books.writelines(newb) #Adding file to the list
newb = {}
newb[n1]=[name, author, publisher]
print 'A New Book Added!'
return newb
def del_book():
print "Deleting Books"
delnum = str(raw_input("Registered Number:"))
if delnum in book:
del book[delnum]
else:
print delnum, "Not Found"
def show_menu():
print '''
1) add new
2) all show
3) delete
4) search
5) Save/out
'''
menu_choice = raw_input('what --> ')
if menu_choice == '1':
add_book()
elif menu_choice == '2':
all_book()
elif menu_choice == '3':
del_book()
show_menu()
books = open(os.path.expanduser("~/Desktop/books.txt")).read()
Your error lies here. If you do not specify a file opening mode, Python will default to 'read' mode, meaning you cannot write to it.
The correct syntax for opening a file for writing is:
books = open('file', 'w')
This page has a table of file access modes down the page.
open() default open the file as read, and that's why you can't write your new book into the text file.

Categories