Writing to text file formatting - python

I have an assignment to make a simple task manager/todo list. This code block is just the part of the program that handles login, new username and password registration. When the user registers that input is written to a text file called user.txt.
Whenever it writes to the text file, it writes like this:(['admin', 'adm1n'])
instead, it should write it like this:admin, adm1n
user_file = open("user.txt","r+")
login = False
while login == False:
new = input("Are you a new user? Y/N:\n").lower()
if new == "y":
print("Please register a new username and password:\n")
new_user1 = input("Please enter a new username:\n").split()
new_pass1 = input("Please enter a new password:\n").split()
new_user2 = input("Please confirm your username:\n").split()
new_pass2 = input("Please confirm your password:\n").split()
user_pass1 = new_user1 , new_pass1
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
elif new == "n":
username = input("Enter your username:\n")
password = input("Enter your password:\n")
valid_user = username
valid_password = password
for line in user_file:
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
if login == False:
print("Incorrect details! Please enter a valid username and password")
What am I doing wrong? I'm sure it's something small.
Thanks in advance!

Because you are making a tuple there. Instead, you should create a string. Here is the corrected version of your code
user_pass1 = new_user1 + ',' + new_pass1
user_pass2 = new_user2 + ',' + new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break

Thanks for your feedback everyone.
I managed to get it figured out. I added an index to it to print the string and it worked just fine.
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
#Writes username and password to text file in format requested.
user_file.write(f'\n{user_pass2[0]}, {user_pass2[1]}')

Related

why closes my python program without fully executing?

I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()
I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...

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

Password - Login not working Python

I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue

Adding new users/passwords to dictionary in python email application

I'm having a bit of trouble with this program I've been working on for part of the final for my ITP 100 class. It's supposed to be an email application where you can log in if you are an existing user, or create a new username and password. I'm able to log into existing users with their passwords, and I can create a new username, but when I try to create the new password for it, I keep getting errors. I'm sure it's because I'm not updating the dictionary properly. I'm still pretty new to Python, so hopefully this all makes sense. Any advice?
Also, my program seems to be stuck in an "if loop..?". Whenever I successfully log into an existing user, it show that I've been logged in, but will also go back to the original question "Are you a registered user? y/n? Press q to quit"
Any help is greatly appreciated. Thank you.
import re
users = {}
users={"nkk202": "konrad", "jfk101": "frederick"}
choice = None
login = None
createPassword = None
createUser = None
createLogin = None
print("Welcome to Kmail. The most trusted name in electronic mail.")
print("\nLet's get started")
while choice != "q":
choice = input("Are you a registered user? y/n? Press q to quit: ")
if choice == "q":
print("Thank you for using Kmail. Goodbye.")
if choice == "n":
print("Okay then, let's set up an account for you then.")
createUser = input("Create login name: ")
if createUser in users:
print("I'm sorry, that username is already in use. Please try another!\n")
else:
createPassword = input("Enter a password: ")
if len(createPassword) <5:
print("I'm sorry, this password is too short. Please try another.")
passValue = {1:'Weak', 2:'Good', 3:'Excellent'}
passStrength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', createPassword):
passStrength['has_upper'] = True
if re.search(r'[a-z]', createPassword):
passStrength['has_lower'] = True
if re.search(r'[0-9]', createPassword):
passStrength['has_num'] = True
value = len([b for b in passStrength.values() if b])
print ('Password is %s' % passValue[value])
users.update((createUser, createPassword))
elif choice == "y":
login = input("Enter your username: ")
if login in users:
password = input("Enter your password: ")
if users[login] == password:
print("Welcome", login, "!")
else:
print
print("I'm sorry, either the password/username was unaccaptable, or does not exist. Please try again. \n")
Seems like you just want
users[createUser] = createPassword

Categories

Resources