Problems with text file appending in python - python

I am having python problems.
I have made a program to ask a user for their email address and it appends it to a text file, after doing some checks, everything is working fine, but it ends up with nothing in the text file, even though no errors show up.
My code is:
def main():
print("Hello and welcome to customer email program!")
count=0
while count < 1:
email=str(input("Email Address: "))
if "#" in email:
if email.islower == True:
count=2
with open("emails.txt", "a") as myfile:
myfile.write(email)
print("File added to databse")
else:
email=email.lower()
count=2
with open("emails.txt", "a") as myfile:
myfile.write(email)
else:
print("That is not an email address, please try again.")
main()
Any help would be greatly appreciated.

I think you should open the file and then CLOSE the file after you append to it:
def main() :
print("Hello and welcome to customer email program!")
done = False
while not done :
email = str(input("What's your email address? "))
if "#" in email :
if not email.lower() == email :
email = email.lower()
done = True
f = open("emails.txt" "a")
f.write(email)
f.close()
else :
print("Please type in a valid email address, "+email+" isn't a valid email address")
main()
Does this fit your needs?

Related

Why doesnt this code continue to remain in the conditional loop for more than one iteration?

i am creating a signup system that saves an email address and password to a file 'users.txt'. the script first checks if the file 'users.txt' contains an entry for the given email address and if found returns 'An Account with that email already exists' and then prompts the user again to enter an email address. the code works the first time returning the error message but if you enter the same email again it does not return with the same error message as intended instead it continues with the rest of the code. How do i remain in the loop until an email address is given that is not in the file? here is my code so far:
#!/usr/bin/env python3
import getpass
class NewUser:
def __init__(self):
self.username = input('Enter your email address: ')
checkUser = NewUser.userExists(self.username)
while True:
if checkUser == False:
self.username = input('Enter your email address: ')
if checkUser == True:
break
self.password = getpass.getpass(prompt='Choose a Password: ', stream=None)
self.confirm = getpass.getpass(prompt='Confirm Password: ', stream=None)
while True:
if self.password != self.confirm:
print('Passwords do not match, try again.')
self.password = getpass.getpass(prompt='Choose a Password: ', stream=None)
self.confirm = getpass.getpass(prompt='Confirm Password: ', stream=None)
if self.password == self.confirm:
break
print('Account has been successfully created')
with open('users.txt', 'a+') as f:
f.write('\n')
f.write(self.username)
f.write(', ')
f.write(self.password)
f.close()
def userExists(username):
with open('users.txt', 'rb') as f:
if bytes(username, encoding='utf-8') in f.read():
print('An account with that email already exists.')
return(False)
else:
return(True)
there are lot of issues in way you have structured your code, but we are going to focus only on problem you mentioned. i m just going to rewrite the code a bit to show what a solution can be hope that helps.
class NewUser:
def __init__(self):
user_exist = True
while user_exist:
self.username = input('Enter your email address: ')
user_exist = NewUser.userExists(self.username)
if user_exist:
print('An account with that email already exists.')
# here prompt for asking email will keep coming till entered email
# is not in given file
pass_match = False
while not pass_match:
self.password = getpass.getpass(prompt='Choose a Password: ', stream=None)
self.confirm = getpass.getpass(prompt='Confirm Password: ', stream=None)
pass_match = self.password == self.confirm
if not pass_match:
print('Passwords do not match, try again.')
print('Account has been successfully created')
with open('users.txt', 'a+') as f:
f.write(self.username+', '+ self.password+'\n')
f.close()
def userExists(username):
with open('users.txt', 'rb') as f:
return bytes(username, encoding='utf-8') in f.read()

ValueError: I/O operation on closed file inside an if statement

I made a login/signup program where the user must type in credentials in order to make an account or enter.
But I have two problems though, one is inside the function 'sign_up()' if the user is attempting to make a pre-existing account it should print the 'This username is taken' statement, but that's not the case. It prints a Value Error called 'I/O operation on closed file' instead.
Then the second problem is, it doesn't print the credentials in a designated file called 'LOG-IN_DATA', it's basically where you store it.
Anyway here is the code:
from class1 import Credentials
def sign_up():
choose_username_data = input("Choose a UserName: ")
choose_password_data = input("Choose your password: ")
Credentials(choose_username_data, choose_password_data)
data = open('LOG-IN_DATA', 'a+')
if choose_username_data not in data:
data.write(str(Credentials))
data.write('\n')
welcome()
data.close()
if choose_username_data in data:
print("This username is taken!")
sign_up()
data.close()
def log_in():
username_data = input("Enter your username: ")
password_data = input("Enter your password: ")
data = open('LOG-IN_DATA', 'r')
data.read()
data.close()
if username_data and password_data in data:
welcome()
elif username_data and password_data not in data:
print("Username or Password does not match or not recognized.")
log_in()
def welcome():
print("Welcome! You made it in!")
def login_or_signup():
signup_var = ('Signup', 'SignUp', 'signup')
login_var = ('Login', 'LogIn', 'login')
prompt_user = input("Welcome! Would you like to Login or Signup?: ")
if prompt_user in login_var:
log_in()
elif prompt_user in signup_var:
sign_up()
else:
print("\nChoose 'Login' or 'Signup'")
login_or_signup()
login_or_signup()
Sorry if the code is too long. I just want problems and potential ones to be eliminated as far as I am concerned.
Anyways thank you in advance!
Try using with statements when manipulating files. It handles flush and close automatically even when errors occur.
For example:
with open("path", 'r') as f:
content = f.read()
instead of:
f = open("path", 'r')
content = f.read()
f.close()
The problem with this line if choose_username_data in data: is that before, you also used data. The cursor in the file is at the end of this file. So when you ask a second time without setting the cursor back to the start of the file, it read nothing. That's why the 2nd statement never evaluates true.
With everything I told you, the sign_up function can be written:
def sign_up():
loop = True
while loop:
choose_username_data = input("Choose a username: ")
choose_password_data = input("Choose your password: ")
creds = Credentials(choose_username_data, choose_password_data)
with open('LOG-IN_DATA', 'a+') as data:
content = data.read()
if choose_username_data not in content:
data.write(str(creds)+'\n')
welcome()
loop = False
# if choose_username_data in content:
else:
print("This username is taken!")

Why does my Python program fail to read the second line of my data file?

I am learning python. I wanted to learn to work with text files, so I decided to make a simple console program.
The program does the following:
Asks if you had already a profile.
If no, then asks to create a username and a password. The information is saved in a text file.
If yes, then asks to input your password and username.
When the user doesn't have a profile, everything works well. When the user has a profile and wants to log in, it doesn't work and I don't know why.
The username is saved in the first line of the text file and the password in the second line, so, I use readlines()[0] and readlines()[1].
The username is recognized correctly, but the password doesn't. I get this error
Traceback (most recent call last):
File "Archivo de prueba.py", line 4, in <module>
print(text_file.readlines()[1])
IndexError: list index out of range
This is the code I wrote:
text_file = open("Archivo de prueba.txt", "r+")
def ask_for_account():
global has_account
has_account = input("Do you have an account? (Write \"Yes\" or \"No) ")
ask_for_account()
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
text_file.write(create_user)
text_file.write("\n")
text_file.write(create_password)
def login():
username = text_file.readlines()[0]
password = text_file.readlines()[1]
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if str(current_user) == str(username) and str(current_password) == str(password):
print("Succesfully logged in.")
else:
print("Invalid username or password")
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
ask_for_account()
text_file.close()
The following code works. I added a few comments to indicate changes.
def ask_for_account():
return input("Do you have an account? (Enter 'Yes' or 'No') ")
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
# Open the file for writing and close it after use.
text_file = open("Archivo de prueba.txt", "w")
text_file.write("{}\n".format(create_user))
text_file.write("{}\n".format(create_password))
text_file.close()
def login():
# Open the file for reading and close it after use.
text_file = open("Archivo de prueba.txt", "r")
lines = text_file.readlines()
text_file.close()
# remove the newline at the end of the input lines.
username = lines[0].rstrip()
password = lines[1].rstrip()
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if current_user == username and current_password == password:
print("Succesfully logged in.")
else:
print("Invalid username or password")
#
# Put program logic in one place after the methods are defined.
#
has_account = ask_for_account()
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
username = text_file.readlines()[0]
password = text_file.readlines()[1]
The first call to readlines() consumes the entire file and there are no lines remaining for the second call to read, so it returns an empty list.
Read the file once and save the lines in a list, then pick the desired lines from the list:
file_lines = text_file.readlines()
username = file_lines[0]
password = file_lines[1]
Also, be aware that readlines() puts a carriage return \n at the end of every line, so you might have to strip that off depending on how you use these values.

How do I loop my password/username login page and read the password/username from an external file?

I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

How can I make a basic program that allows someone to sign in to an account previously created?

I am trying to make a python program that will allow a user to sign up or sign in, and I am currently doing so by creating a file that stores every username and its password. Right now, it is not writing to the file, and I was wondering if anyone could tell me what I'm doing wrong. Please forgive me if it is a stupid error, I am not very experienced with python, but I can still make a basic program. This is my code:
# -*- coding: utf-8 -*-
from time import sleep
def signin():
usrlist = open("users.txt", 'w+')
complete = False
while (complete == False):
usr = raw_input("Username: ")
pwd = raw_input("Password: ")
usrinfo = (usr + ":" + pwd)
if (usrinfo in usrlist.read()):
print("Welcome back " + usr + ".")
complete = True
else:
print("Username or Password incorrect. Please try again.")
def signup():
usrlist = open("users.txt", 'w+')
usravailable = False
while (usravailable == False):
newusr = raw_input("Please choose a Username: ")
if (newusr in usrlist.read()):
print("Username taken. Please choose again.")
else:
usravailable = True
newpwd = raw_input("Please choose a password: ")
oldusrlist = usrlist.read()
usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")
print("Thank You. Please Sign in.")
signin()
print("Please Choose An Option:")
print("1. Sign In")
print("2. Sign Up")
inorup = input()
if (inorup == 1):
signin()
elif (inorup == 2):
signup()
Also, if you have any suggestions about how I could do this differently, or better(even if it's using a different language) Thank you and I appreciate your help.
EDIT:
If anyone can give me information on doing a program like this either using JSON, javascript, or multiple files that can store larger amounts of data about each account, please tell me how in the comments or an answer. I appreciate the help.
To fix your not saving issue, you need to do two changes:
1) in your signin() routine, change the line 'usrlist = open("users.txt", 'w+')' into 'usrlist = open("users.txt", 'r')
2) in your singup() routine, after the line 'usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")', add: 'usrlist.close()'
Then you should be able to see the stuff got saved.
here is a way to use json
import json
import os
FILENAME = "./f.json"
# init the data file
def init_data():
with open(FILENAME, "wb") as f:
json.dump({}, f)
def load_content():
with open(FILENAME) as f:
infos = json.load(f)
return infos
def save_content(content):
with open(FILENAME, "w+") as f:
json.dump(content, f)
return True
def save_info(username, password):
infos = load_content()
if username in infos:
return False
infos[username] = password
save_content(infos)
return True
def sign_in(username, password,):
status = save_info(username, password)
if not status:
print "username exists"
def login(username, password):
infos = load_content()
if username in infos:
if password == infos[username]:
print "login success"
return True
else:
print "password wrong"
return False
else:
print "no user named %s" %username
if __name__ == "__main__":
# here is some simple test
os.system("rm -f %s" %FILENAME)
if not os.path.exists(FILENAME):
init_data()
# login fail
login("hello","world")
# sign_in
sign_in("hello", "world")
# login success
login("hello","world")
# sign_in fail
sign_in("hello", "world")
# login fail
login("hello", "hello")

Categories

Resources