Why can't I write to a file despite using "append" mode? - python

I'm trying to create a basic login system with Python that only includes a username. Here is a snippet of what I'm having issues with.
I added a few usernames to the .txt file and it can find conflicts or login properly but it can't actually register a username. I've done some research and am opening the file in "append" mode and using the write command.
def register():
file1 = open("C:/test/User_Dat.txt", "a")
global username
username = str(input("Please enter a username \n")).lower()
readfile = file1.read()
if username in readfile:
print('The user', username, 'has already been created.')
welcome()
else:
print('The user', username, 'has been created!')
file1.write(username)
file1.write("\n")
file1.close()
login()
But I still get an error like this:
io.UnsupportedOperation: not writable
Why is the file not writable?

EDITED:
You are opening file in reading mode. Fix this line as follows:
file1 = open("C:/test/User_Dat.txt", "r+")
Documentation:
https://docs.python.org/3/library/functions.html#open

Related

When i try to make python write user input to a txt file, it doesn't

i am learning python, and i wanted to create a little login and register program, that writes the username and the password to a txt file (so that it can be later used), i am currently working on the register function, when i try to write to the txt files it does nothing, i tried doing a with loop, a .flush() and .close() but neither of them saves the info.
Here's my code:
username.write = input ('username > ')
password = open("password.txt", "w")
password.write = input ('password > ')
print('Welcome.')
username.close()
password.close()
What am i missing?
Edit.
Neither 3 of the solutions to the suggested question work for me...
Get your input and store them in two variables and then write them to files:
username = input ('username > ')
password = input ('password > ')
with open('usernames.txt', 'w') as userFile:
userFile.write(username)
with open('passwords.txt', 'w') as passFile:
passFile.write(password)
yourfile.open(filename,'w')
username = input()
password = input()
yourfile.write(username)
yourfile.write(password)
yourfile.close()

Getting python to write to new line in a FIle

I am trying to make a simple login system because I am bored and want to learn python, I am trying to store the usernames in a file but new usernames are just replacing the current one in the list.
#USENRAME UNENCRYPTED PASSWORD SYS
print ("WOuld you like to login or signup (login/signup)")
choice = input()
if choice == "signup":
print ("Can you enter your username please?")
username = input()
with open('username') as f:
if username in f.read():
print("That Username already exists")
else:
f= open("username","w+")
f.write(username + "\n")
f.close()
Say if the first username I enter is "Dave" and then I close the program, the next username I register with being "Harry" The "Harry" will just replace the "Dave" In line one of the "usernames" file.
You dont need to open your file twice, but when you open it the first time what you you want to be able to do is append to what is already there.
with open('username.txt','a+') as f:
if username in f.read():
print("That Username already exists")
else:
f.write(username + "\n")
Try reading this if you're unsure.
https://www.guru99.com/reading-and-writing-files-in-python.html

How can I create a login program that checks for availability on Python?

I'm making a user login for a little project I'm working on at school, practising my file handling and whatnot. For the most part, it's going fine, but I'm having trouble when I try and create new users. The new user needs to have an original username and password to be created, otherwise, it should tell them that their choice is unavailable. For some reason, it works fine with the first username and password in the files and makes the user retry. But when I try and create a new user with a name that I know I shouldn't be able to, it lets me.
def signUp():
username = str(input("\nPlease enter your new username "))
file = open ("usernames.txt","r")
for x in file:
if username in x:
print ("\nThat username is already in use, please try another")
signUp()
else:
print ("Your username is now ",username)
file.close()
password = input("\nPlease create a password ")
file = open ("passwords.txt","r")
for x in file:
if password in x:
print ("\nThat password is already in use, please try another")
signUp()
else:
print ("Your password is now ", password," Don't forget it")
file.close()
file = open ("usernames.txt","a")
file.write (username)
file.write ("\n")
file.close()
file = open ("passwords.txt","a")
file.write (password)
file.write ("\n")
file.close()
print ("\nYour login details have been saved")
print ("Please login")
logIn()
In the username file, it has the names:
Alex
Josh
The password file has:
123qwe
ewq321
The code works for Alex and 123qwe and stops them from being repeated, but not for Josh or ewq321.
At the moment, I'm not looking for any other improvements. I'll refine it all later. For now, I just need help with this little predicament. I understand that my explanation is a little confusing, so it might help to copy what I've already done and play around with it. Obviously, this isn't the whole code, so it might not make perfect sense.
The problem is in both loops, exactly on the else clause.
Your code checks that if the only first username already exists that's because you introduced an else on the loop, and also you need to get out of the program if the username already exists using return.
Here is the new code:
def signUp():
username = str(input("\nPlease enter your new username "))
file = open ("usernames.txt","r")
for x in file:
if username in x:
print ("\nThat username is already in use, please try another")
signUp()
return
print ("Your username is now ",username)
file.close()
password = input("\nPlease create a password ")
file = open ("passwords.txt","r")
for x in file:
if password in x:
print ("\nThat password is already in use, please try another")
signUp()
return
print ("Your password is now ", password," Don't forget it")
file.close()
file = open ("usernames.txt","a")
file.write (username)
file.write ("\n")
file.close()
file = open ("passwords.txt","a")
file.write (password)
file.write ("\n")
file.close()
print ("\nYour login details have been saved")

error outputting file with python 3.0

I am not sure why I am receiving this error. Everything in my program seems to be working perfectly. the program is basically a simple administration system to store username and password accounts.
the error i get is, ValueError: I/O operation on closed file.
the program successfully writes the first account, but the other accounts do not get stored in the .txt file
here is my code where i am getting the error
if savedata == 'y':
print ("\nData Successfuly Saved!")
filehandle = open(filename, "r+")
for username, password in store_data.items():
print(username, ":",password)
password = password.replace("\n","")
filehandle.write(username) # it says this line is my error
filehandle.write(":")
filehandle.write(password)
filehandle.write("\n")
filehandle.close()
else:
("Exiting Application Terminal...")
The following should fix matters:
if savedata == 'y':
print ("\nData Successfully Saved!")
with open(filename, "w") as filehandle:
for username, password in store_data.items():
print(username, ":", password)
password = password.replace("\n","")
filehandle.write("{}:{}\n".format(username, password))
else:
print("Exiting Application Terminal...")
You were closing the file after each iteration, as you only opened it once, this is why only one entry was saved.
It is also safer to use Python's with construct which will automatically take care of closing the file for you.
If you wish to append to an existing file, use "a" as the mode.
You should open the file for writing:
filehandle = open(filename, "w")

Search and write lines of multiple strings in python?

def info(): #Here you can write your password and username.
Username = raw_input ("Username: ")
Password = raw_input ("Password: ")
print("")
for line in open('/home/hello/Usernames.txt'):
if Username == Username in line: #Checks if username is available.
print ("Username is already taken!\n")
info()
else:
User = open("/home/hello/Usernames.txt", "w") #Registers username.
User.write(Username)
Psw = open("/home/hello/Passwords.txt", "w") #Registers password.
Psw.write(Password)
print ("You have succsesfully registered!") #If you managed to register.
break
info()
This is an account registerer that can register both username and password. But I need help with something... How can I make it check multiple lines of strings in a file, and how can I make the program write a new line of string in the text files when I register without replacing the old string?
Open the file for appending ('a') mode instead of writing ('w') which truncate the file.

Categories