new project :: adv. contactbook , but i am facing some issues - python

i am a beginner at python , i was working with this project from a long time.
in this project the user should be able to create different account . and the account username and password should be kept in .txt file. then when the user wish they can create a contact book and then write some contact details. the user should also open the contact book whenever they want. but i am getting of error . so could somebody help me.
this is the codes --
name=(user2+".txt")
contact_book=open(name,"a")
contact_book.write("\n")
option=input("hello,do you want to save a new contact:(yes/no) ")
space=(" ")
def openbook():
option=input("do you want to open the contacts (yes/no)")
if option == ("yes"):
openfile=open(name,"r")
print(space)
openfile=openfile.read()
print(openfile)
contact_book.close()
def book():
print("ok")
name=input("what is the name?: ")
print(space)
phone=input("what is the phone number?: ")
print(space)
address=input("what is the address?: ")
contact_book.write("\n")
contact_book.write(name+" "+phone+" "+address)
contact_book.write("\n")
print("ok,done")
print(space)
contact_book.close()
option1=input("do you want to save a new contact:(yes/no)")
while option1==("yes"):
book()
if option1==("no"):
openbook()
x=2
while x==2:
if option==("yes"):
book()
delete=input("do you want to delete the contact book!! (yes/no)")
if delete == ("yes"):
os.remove(name)
if option ==("no"):
openbook()
delete=input("do you want to delete the contact book!! (yes/no)")
if delete == ("yes"):
os.remove(name)
if delete==("no"):
print("ok")
input("")
if delete == ("yes"):
os.remove(name)
x=x-2

Related

Assistance with a Login System & Printing a Text File

I have a program that asks the user for a username and password, then checks a text file to see if that username/password are in there. Then it is supposed to print the contents of the text file to screen. A couple of issues:
It ALWAYS takes two attempts to successfully log in, even if the username/password are correct.
On successful login, the contents of the text file are not printed.
Would very much appreciate some guidance on why these things are happening, and how they can be resolved!
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
fileRead=open('accounts.txt','r')
fileContents = fileRead.read()
flag=False
while True:
line=fileRead.readline()
lineLength=len(line)
if lineLength==0:
break
lineItem=line.split()
if username.strip()==lineItem[0] and password.strip()==lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print(fileContents)
flag=True
break
if flag==False:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
I would try something like this.
def print_file_contents(file_name):
with open(file_name) as f:
for line in f:
print(line)
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
file = 'accounts.txt'
flag = False
for line in open(file).readlines():
lineItem=line.split()
if username.strip() == lineItem[0] and password.strip() == lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print_file_contents(file)
flag=True
break
if not flag:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
However I haven't really modified what the code does, and I suspect the issue comes with how the text file is formatted.
I also assume this is a project and not actual passwords stored in a .txt file which wouldn't be a great idea.

Searching for specific information in a file

So, I have a program that acts like a local login/signup system. It asks the user if they want to signup, or login. If they signup, they shall type a username and password in a certain format and it puts it in a file.
If they choose to login, the program will assume that what they're about to type in is located in the file. The intended use is that if it is in the file, it will say that the account is valid. If the thing that the user typed in isn't located in the file, it should say that it is not a valid account.
As of now, the output always says that the account isn't valid, even though it is in the file. Here is the login portion of the code:
elif sol == "l":
os.system("clear")
print("You have chosen to login.")
time.sleep(2)
os.system("clear")
datasearch = input("What is your username and password?(username/password): ")
with open ("user_database.txt", "r") as searchdata:
if datasearch in os.linesep:
os.system("clear")
print("This is a valid account!")
time.sleep(3)
os.system("clear")
quit()
else:
os.system("clear")
print("This is not a valid account!")
time.sleep(3)
os.system("clear")
You are not searching the file. You are checking if the users input is in os.linesep.
You should put something like if datasearch in searchdata.read(): inplace of if datasearch in os.linesep: in your code.

How do I run while loop that appends a text file?

I'm a beginner trying to do a short learning exercise where I repeatedly prompt users for their name and save those names to guest_book.txt, each name in a new line. So far, while loops are always giving me trouble to get them working properly.
In this case, the program ends when I enter the first name, here's the code:
"""Prompt users for their names & store their responses"""
print("Enter 'q' to quit at any time.")
name = ''
while True:
if name.lower() != 'q':
"""Get and store name in guestbook text file"""
name = input("Can you tell me your name?\n")
with open('guest_book.txt', 'w') as guest:
guest.write(name.title().strip(), "\n")
"""Print greeting message with user's name"""
print(f"Well hello there, {name.title()}")
continue
else:
break
It runs perfectly when I omit the with open() block.
In a more pythonic way:
with open('guest_book.txt', 'w') as guest:
while True:
# Prompt users for their names & store their responses
name = input("Can you tell me your name?\n")
if name.lower() == 'q':
break
# Get and store name in guestbook text file
guest.write(f"{name.title().strip()}\n")
# Print greeting message with user's name
print(f"Well hello there, {name.title()}")
Can you tell me your name?
Louis
Well hello there, Louis
Can you tell me your name?
Paul
Well hello there, Paul
Can you tell me your name?
Alex
Well hello there, Alex
Can you tell me your name?
q
>>> %cat guest_book.txt
Louis
Paul
Alex
First try to read an error which was shown by Python.
TypeError: write() takes exactly one argument (2 given)
Next you answer a name after if state. I make some changes with your code and move open to begin of code (and thanks to Corralien for review):
print("Enter 'q' to quit at any time.")
with open('guest_book.txt', 'w') as file:
while True:
name = input("Can you tell me your name?").title().strip()
if name.lower() == 'q':
break
if name:
file.write('{}\n'.format(name))
print('Well hello there, {}'.format(name))

Python If Statement question login system easy

The first thing to do is write "1" and then enter username and password. After that, the max number of account is 1 and you can then use the "2" to login.
First time asking a question so I am sorry if this is like a dumb question or something. My code is as following:
https://imgur.com/a/dAaYf2u - NEW LINK
Code:
print("Type 1 for Create user. Type 2 for login")
Choice = input("Number here: ")
if Choice == ("1"):
print("Welcome to the Create a user interface")
Username = input("Username: ")
Password = input("Password: ")
if Password.count("!") > 0:
print("Not valid - no special characters!")
else:
file = open("account.txt", "w")
file.write(Username)
file.write("\n")
file.write(Password)
file.close()
elif Choice == ("2"):
print("Welcome, please type your Username and Password")
Loginu = input("Write username here: ")
Loginp = input("Write password here: ")
file = open("account.txt", "r")
first_line = file.readline()
if Loginu == first_line:
print("you're logged in")
else:
print("fail")
It's very basic and so on. What I don't understand is why the if Loginu == first_line can't read the first_line variable... It just jumps directly to else:
I hope it helps and I know my code is very basic lol.
My advice:
follow pep8, use meaningful names for variables
split your code into functions
use infinite loop for your "menu"
even better use some package that helps with building such applications (click?) rather then reinvent the wheel
Read your file with with open(...) as f: context manager
It's probably good idea to read whole file and build dictionary instead of depending on the login to be exactly identical with first line
use strip() to remove white characters (like newline)
check that line you are looking at is not empty
if you've opened file without context manager for writting, you need to close it before opening it again for reading
use debugger to check what's exactly result of readline

How to create a python dictionary that will store the username and password for multiple accounts

The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.
Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).
import pickle
import time
def loaddict():
try:
with open("dictAcc.txt", "rb") as pkf:
return pickle.load(pkf)
except IOError:
with open("dictAcc.txt", "w+") as pkf:
pickle.dump(dict(), pkf)
return dict()
def savedict(dictAcc):
with open("dictAcc.txt", "wb") as pkf:
pickle.dump(dictAcc, pkf)
def userPass():
dictAcc = loaddict() #Load the dict
checkAccount = raw_input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = raw_input("Please Set Your New Username: ")
password = raw_input("Please Set Your New Password: ")
if (userName in dictAcc):
print("Username is taken")
userPass()
else:
dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
savedict(dictAcc) #Save the dict
time.sleep(1.5)
# dataInput() Code ends
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = raw_input("Type in your Username: ")
loginPass = raw_input("Type in your Password: ")
dictAcc = loaddict() #Load the dict
if (tries < 3):
for key in dictAcc:
if (loginUserName == key and loginPass == dictAcc[key]):
print("You have successfully logged in!")
# dataInput() Code ends
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(3)
tries=1 #To restart the tries counter
login()
global tries
tries=1
userPass()
There are different ways to do this. I'll mention two.
As you noticed, all variables created by your program are erased when the program finishes executing.
One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.
However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.
You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.
How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.
Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.
So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.
A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.

Categories