I'm working on a contact book application to improve my python skill, so far I've created functions to add new contact, view existing contact, but I'm stuck on a function to edit them, I don't know how to tackle this task (note that editing and adding information is based on user input), currently the only information this application is recording are name, phone number and/or email (if user entered an email).
I'm storing the contacts in individual files, where file name is the contact name, and the contact are his/her information (first line is always the phone number, second line if present is the email) and I'm supposing for now that all contact have phone numbers
As I think that the edit function will be similar to the add, here is the add function
def add_contact():
if question == 'add':
contact_name = input('Enter the name of the contact you want to add: ')
join_input = dir_path + "\\" + contact_name + ".txt"
#join_input = os.joinpath(dir_path, contact_name)
os.makedirs(dir_path, exist_ok=True)
if os.path.exists(join_input):
print('this contact is founded')
else:
while True:
contact_number = input("Enter the contact's number: ")
if not contact_number.isdigit():
print('Type a number next time.')
continue
else:
f = open(join_input, "a")
f.write('Phone number: ' + contact_number)
f.write('\n')
f.close()
email_print = input('Would you like to add an email address? Type yes or no: ').lower()
if email_print == 'yes':
contact_email = input("Enter the contact's email: ")
f = open(join_input, "a")
f.write('Email Adress: ')
f.write(contact_email)
f.close()
print('Contact', contact_name, 'is succesfuly created!')
break
elif email_print == 'no':
print('Contact', contact_name, 'is succesfuly created!')
break
else:
continue
and here is an example of it running
Do you want to add, view, or delete contact? Enter add, view or delete: add
Enter the name of the contact you want to add: test
Enter the contact's number: 0129309123
Would you like to add an email address? Type yes or no: yes
Enter the contact's email: test#gmail.com
Contact test is succesfuly created!
My progress so far in edit_contact is the following
def edit_contact():
while True:
if question == 'edit':
contact_edit = input('Enter the name of the contact you want to add: ')
join_edit = dir_path + "\\" + contact_edit + ".txt"
if os.path.exists(join_edit):
contact_input_delete = input('Do you want to edit phone number, or email adress? Type number, or email: ').lower()
if contact_input_delete == 'number':
with open(join_edit, 'w') as file:
data = file.readlines()
file.writelines(data)
else:
print("This contact doesn't exists.")
continue
if you want to see my whole function, you can check it on github: Github
Since the file content will always be limited to two lines, you can reuse the whole add_contact() function, with a minor change, in the first open of the file use "w" argument, f = open(join_input, "w"), this will clear whatever is stored previously in the file, the second open should stay "a" to not clear the phone number. And of course you need to do some cosmetic changes (print messages), anyways the new code will be:
def edit_contact():
contact_name = input('Enter the name of the contact you want to add: ')
join_input = dir_path + "\\" + contact_name + ".txt"
os.makedirs(dir_path, exist_ok=True)
if not os.path.exists(join_input):#we need to reverse the condition here, if the contact is found we can edit it, otherwise we need to skip the use's input
print('this contact does not exist')
else:
while True:
contact_number = input("Enter the contact's number: ")
if not contact_number.isdigit():
print('Type a number next time.')
continue
else:
f = open(join_input, "w")
f.write('Phone number: ' + contact_number)
f.write('\n')
f.close()
email_print = input('Would you like to add an email address? Type yes or no: ').lower()
if email_print == 'yes':
contact_email = input("Enter the contact's email: ")
f = open(join_input, "a")
f.write('Email Adress: ')
f.write(contact_email)
f.close()
print('Contact', contact_name, 'is succesfuly created!')
break
elif email_print == 'no':
print('Contact', contact_name, 'is succesfuly created!')
break
else:
continue
Related
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#with open('contact_list.txt','a') as file:
# file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)
I'm a student who is doing my Python assignment. Thing is, our lecturer is really strict on us not using python built ins and also refuses to check our code before submission and I'm having the hardest time trying to get my code to work properly during registration.
My problem currently is that I want the code to prompt an error from the program itself when the user tries to register with a taken username. However, it keeps running different errors regardless of how I try to fix it. Can anyone please point me in the right direction or tell me what's wrong with my code? I'd be really grateful for any help.
def grant():
print("Helllooooo")
def begin():
while True:
print("Welcome to the Freshco Groceries App!")
option = input("Are you a new or returning user?\n"
"Enter 1 if you would like to LOGIN\n"
"Enter 2 if you would like to register\n"
"Enter 3 if you would like to exit the program\n")
if option=="1":
access(option)
break
elif option=="2":
access(option)
break
elif option=="3":
print("Thank you! Have a good day.")
exit()
else:
continue
def access(option):
if(option=="1"):
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
login(name,password)
else:
print("First step: Please choose a username and a unique password.")
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
register(name,password)
newuser()
def login(name,password):
success=False
file = open("user_details.txt","r")
for line in file:
a,b = line.split(",")
if (name in a) and (password in b):
success=True
break
file.close()
if(success):
print("You have successfully logged in! Happy shopping!")
grant()
else:
print("Wrong username or password entered.")
def register(name,password):
exist = False
while True:
file = open("user_details.txt", "r")
for line in file:
line = line.rstrip()
if (name == line):
exist = True
break
else:
pass
file.close()
if (exist):
print("Username has been taken. Please try again with a new one.")
break
else:
file = open("user_details.txt","a")
file.write("\n" + name + "," + password)
print("You have successfully registered! Welcome to the Freshco Family!")
grant()
break
def newuser():
print("Before you start using the app, please fill in the details below.")
alldata = []
while True:
newdata = []
nname = input("Please enter your full name:\n")
newdata.append(nname)
while True:
ngender = input("Are you female or male?\n"
"1: female\n"
"2: male\n")
if ngender=="1":
fingender="female"
newdata.append(fingender)
break
elif ngender=="2":
fingender="male"
newdata.append(fingender)
break
else:
print("INVALID INPUT")
continue
naddress = input("Please enter your address:\n")
newdata.append(naddress)
nemail = input("Please enter your email address:\n")
newdata.append(nemail)
ncontact = input("Please enter your contact number:\n")
newdata.append(ncontact)
ndob = input("Please enter your dob in this format: <DD.MM.YY>\n")
newdata.append(ndob)
alldata.append(newdata)
print(newdata)
break
print("Thank you for entering your information, you will be redirected now!")
grant()
begin()
thank you so much! T-T
Hello I am a student and I have been researching on here for way too long to find answers to how to make this login page actually work. All the pages I have found have made them in different ways that don't work for me. Can anyone off this code push me on the right track to create this. I have got my signup page to work though.
def signup():
users = open("login_signup.txt","a")
user = []
username = input("What do you want your username to be?: ")
password = input("What do you want your password to be?: ")
user.append(username)
user.append(password)
users.write(username + "," + password)
users.write("\n")
print("You have successfully signed up")
def login():
with open("login_signup.txt","r") as users:
usersusername = input("What is your username?: ")
userspassword = input("What is your password?: ")
Btw the format off the text in the file is: username,password
Then it goes to a new line after the next person wants to create an account.
Thanks to anyone who can help :)
Since you're still having problems here's a modification of your code that works.
def signup():
with open("login_signup.txt","a") as users: # context manager is preferred over pure open/close
#user = [] # not used so remove
username = input("What do you want your username to be?: ")
password = input("What do you want your password to be?: ")
#user.append(username) # not used so remove
#user.append(password) # not used so remove
users.write(username + "," + password)
users.write("\n")
print("You have successfully signed up")
def login():
usersname = input("What is your username?: ")
userspassword = input("What is your password?: ")
with open("login_signup.txt", "r") as users:
for line in users: # iterating over login file a line at a time
login_info = line.rstrip().split(',') # rstrip() removes the '\n' at end of string
# split(',' split string on comma
if usersname == login_info[0] and userspassword == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
Exmaple Run
sigup()
# Out:
# What do you want your username to be?: john
# What do you want your password to be?: paul
# You have successfully signed up
login()
# Out:
# What is your username?: john
# What is your password?: paul
# Correct credentials!
# True
Currently I'm in the process of making a program where you can both login and register and the username/password are stored in a separate .txt file.
Registering is working fine, the username and password is written without issue but I am having issues with reading from the file in both userRegister and userLogin
The .txt file is formatted by username,password and I was wondering how I would go about reading from the file with the intention of comparing loginUsername and loginPassword to username_password and comparing registerUsername to existing usernames to ensure there are no duplicates.
username_password = open("savedCredentials.txt", "r+")
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
registerPassword()
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
username_password.close()
A few things:
You aren't calling any functions in your above code, so nothing will run as it stands.
You cannot iterate a Text wrapper, you can get around this by just reading your file by .read()
If you close() the file outside of your functions, you'll get an error that the file is closed, close the file within your function instead (whenever the user is done).
It appears once you go through the conditional if search, the .read() doesn't work anymore for the 2nd round. Don't quite know why (maybe someone else here can go into more detail), but the workaround is instead convert your file to a list, and search through that instead.
The below works, but it is a bit ugly (I have to go know, but wanted to post this real quick so you have at least a working example, and can build off of it).
username_password2=[]
with open("savedCredentials.txt", "r+") as file:
for lines in file:
a=lines.replace(',',' ')
b=a.split()
username_password2.append(b)
username_password = [x for y in username_password2 for x in y]
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
while True:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
register.close()
break
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print(username_password)
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
startMenu()
You have to add the read function to your file opening.
replace the line username_password = open("savedCredentials.txt", "r+")
by
username_password = open("savedCredentials.txt", "r+").read()
then you have to remove the line username_password.close()
also, you need to call your startMenu function so add startMenu() at the bottom of your code.
This is my code:
import time
print("Welcome to the quiz")
print("Would you like to login with an existing account or register for a new account?")
def login():
userQ = input("Please enter your username: ")
passQ = input("Please enter your password: ")
#In progress of making...
def register():
print ("Your username will now be created from your first name and age.")
fname = input("Please enter your first name: ")
age = input("Please enter your age: ")
fname2 = fname[:3]
username = fname2 + age
print ("Your username is {}".format(username.upper()))
password = input("Please enter a password for your new account: ")
time.sleep(1.0)
print ("Username: {}".format(username))
print ("Password: {}".format(password))
with open("UserPass.csv", "w") as f:
for line in f:
file = line.split(",")
f.write(username) in file[0]
print ("ACCOUNT CREATED")
login()
class validation(Exception):
def __init__(self, error):
self.error = error
def printError(self):
print ("Error: {} ".format(self.error))
def mainError():
try:
raise validation('Please enter a valid input')
except validation as e:
e.printError()
def Menu():
while True:
options = ["Login", "Register"]
print("Please, choose one of the following options")
num_of_options = len(options)
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
try:
uchoice = int(input("? "))
if uchoice == 1:
print("You chose to " + options[uchoice - 1])
login()
break
elif uchoice == 2:
print("You chose to " + options[uchoice - 1])
register()
break
elif (uchoice - 1) > len(options):
mainError()
except ValueError:
mainError()
Menu()
In my code, if the user chooses to register for a new account, it runs the 'register()' method. After the user are their username and password in the method, it writes it to a csv file and then calls the login() method. BUT, instead... it somehow runs the Menu() method instead and ignores my login().
In addition, after the end of the register method is reached, it prints an error message that I made with my 'Class Validation(Exception) and 'mainError()' which I don't want it to - I don't understand why it does this as I have not called mainError().
An example of when I run the code and choose to register:
Welcome to the quiz
Would you like to login with an existing account or register for a new account?
Please, choose one of the following options
press 1 to Login
press 2 to Register
? 2
You chose to Register
Your username will now be created from your first name and age.
Please enter your first name: Siddharth
Please enter your age: 16
Your username is SID16
Please enter a password for your new account: shamrock
Username: Sid16
Password: shamrock
Error: Please enter a valid input
Please, choose one of the following options
press 1 to Login
press 2 to Register
?
As you can see, it goes to the Manu() instead of login() after the registration and before it, prints "Error: Please enter a valid input" when there is no need.
How can I fix this. Thank you!
Change
with open("UserPass.csv", "w") as f:
for line in f:
file = line.split(",")
f.write(username) in file[0]
to
with open('UserPass.csv', 'a') as f:
f.write('whatever text you want to save')