python readlines() function - python

i just started learning file handling using pthon and tries this as a code but for some reason my readlines() function returns an empty list
i have a name and password saved in the UsernameAndPassword.txt file
path1="C:/Users/om/UsernameAndPassword.txt"
f1=open(path1,'a+')
l1=f1.readlines()
print(l1)
def main():
un=input("Enter Username: ")
if un in l1:
i1=l1.index()
p1=l1[i1+1]
pcheck1=input("Enter Password: ")
if pcheck1==p1:
print("Succesfully Logged In!")
def main2():
f2=input("Enter Path of file you want to Access or Path of file you want to create\n")
if f2.exists()==True:
open(f2,'a+')
input1=input("Enter Text you want to write into the File(Enter Blank to stop and a space to leave a line)\n")
while True:
input2=input("\n")
if input2=="":
break
else:
f2.write(input1)
f2.write(input2)
input3=input("Do you want to Read the file?\n")
if input3=='Yes' or input3=='yes':
r1=f2.read()
print(r1)
else:
print("Do you want to access another file?")
input3=input("")
if input3=='yes' or 'Yes':
main2()
else:
print("Thank you for using this :)")
else:
print("File Path Invalid!")
input4=input("Try Again?\n")
if input4=='yes' or 'Yes':
main2()
else:
print("Thank you for using this :)")
main2()
else:
print("Wrong Password")
main()
else:
print("Wrong Username")
input5=int(input("Sign up(Enter 1) or Try again(Enter 2)\n"))
if input5==2:
main()
elif input5==1:
inp6=input("Enter New Username: ")
inp7=input("Enter Password: ")
f1.write(inp6)
f1.write(inp7)
main()
else:
print("Invalid Input")
print("Thank you for using this :)")
f2.close()
f1.close()
main()

a+ is a file mode which effectively means "able to append and read". In particular, since we're appending, it starts at the end of the file rather than the beginning. You can think of it as like a cursor in Notepad or your favorite text editor: When you open a file in r mode, the cursor starts at the beginning and has the whole file to read, but when you open in a mode, the cursor starts at the end of the file so that subsequent writes don't overwrite existing content.
In your case, since you're only ever reading from the file, just use the r mode.
f1 = open(path, 'r')
If you really need a+ (again, the snippet you've shown us doesn't, but your real requirements may differ), then you can manually seek to the beginning of the file to read.
f1 = open(path, 'a+')
f1.seek(0)

Related

Why isn't Python read() function working?

I want to write a reminder program using python. But for some reason, when I read the file it returns nothing. Here's my code,
print ("(1)Add something to list\n(2)Read my lists")
option = input ("Please select an option: ")
myFile = open ("Reminder.txt", "a+")
if option == '1':
ask = input ("What do you want to remember: ")
myFile.write (ask + "\n")
myFile.close()
print ("Successfully added in database")
elif option == '2':
AllFileContents = myFile.read()
print (AllFileContents)
else:
print ("Please select an existing option!")
And this is the output I get after adding something to list(I'm using microsoft visual studio):
https://i.stack.imgur.com/DuS9W.png
Please help.
Try using seek -
print ("(1)Add something to list\n(2)Read my lists")
option = input ("Please select an option: ")
myFile = open ("Reminder.txt", "a+")
if option == '1':
ask = input ("What do you want to remember: ")
myFile.write (ask + "\n")
myFile.close()
print ("Successfully added in database")
elif option == '2':
myFile.seek(0)
AllFileContents = myFile.read()
print (AllFileContents)
else:
print ("Please select an existing option!")
Reference - seek
seek(0) sets the cursor back to the first part of the file , so that you can read the file from the start (basically the whole file.)
Use the open() function without a+ mode. A+ mode puts the cursor at the end of the file.

Python: im trying to write a text file but it just keeps getting cleared

I have been searching for a while but i cant find anything. I'm trying to save whatever i type to a text file with the line number next to it but right after something gets put on the text file, everything in the file just disappears. I'm pretty new to python so i don't know too much.
Main code:
import time, sys, random, os
RR = open("import.txt","r")
Read = RR.read()
new = open("import.txt","a")
edt = open("import.txt","w")
linenum = len(open("import.txt").readlines( ))
prefix = (str(linenum)+"- ")
def replace_line(file_name, line_num, text):
lines = open(file_name, 'r').readlines()
lines[line_num] = text
edt.writelines(lines)
edt.close()
RR.close()
print(Read)
print("What would you like to do?\n")
print("\nNew|Reload|Edit\n")
ask = input()
if ask == "New":
print("Please enter your text.\n")
pen = input()
new.write(str(prefix)+(pen))
new.close()
print("\n\033[1;32m Complete\033[0m \n")
time.sleep(1)
os.system('clear')
exec(open("Reload.py").read())
elif ask == "new":
print("Please enter your text.\n")
pen = input()
new.write(str(prefix)+(pen))
new.close()
print("\n\033[1;32m Complete\033[0m \n")
time.sleep(1)
os.system('clear')
exec(open("Reload.py").read())
elif ask == "Edit":
print("What line would you like to edit?\n")
num = input("Line number: ")
print("Please enter your text.\n")
pen = input()
replace_line("import.txt", (num), (str(prefix)+(pen)))
new.close()
print("\n\033[1;32m Complete\033[0m \n")
time.sleep(1)
os.system('clear')
exec(open("Reload.py").read())
elif ask == "Reload":
exec(open("Reload.py").read())
Reload code:
import time, sys, random, os
print("Please Wait.")
time.sleep(1)
os.system('clear')
time.sleep(1)
exec(open("main.py").read())
First of all, you're not supposed to open the same file multiple times, if you want to be able to read and write you can merge the two parameters "r" and "w" into "rw" for example.
Second, you can make use of the operator OR when you check your input, like:
if ask == "New" or ask == "new":
or
if ask.lower() == 'new':
Using the above "if" condition will make it case insensitive.
I noticed you used a code to call your main code. You're not supposed to do that either, in these cases where we wanna keep on doing things we use a while loop. Like this:
while input() != "nothing":
#put your code here
This will keep your code on asking what you wanna do until you type "nothing".
Close your file object only in the end of your code, since opening them costs quite a lot if your file is considerably big or/and you keep on doing this on a loop.

Error code when trying to write to a text file

Basically I started Python a couple of days ago and wanted to create a program that could read and write files. Problem is I get this error:
io.UnsupportedOperation: not writable
choice = input("Open / Create file: ")
if choice == 'Create' or choice == 'create':
new_file_name = input("Create a name for the file: ")
print(open(new_file_name, "w"))
text = input("Type to write to file: \n")
file2 = open(new_file_name)
print(file2.write(text))
print("Reading file...")
print(open(new_file_name, "r"))
print(file2.read())
elif choice == 'Open' or choice == 'open':
filename = input("File name or directory: ")
file = open(filename)
open(filename, "r")
time.sleep(1)
print("Reading file...")
time.sleep(1)
print(file.read())
choice2 = input("Write to file? Y/N \n")
if choice2 == 'Y' or choice2 == 'y':
text2 = input("Type to write to file: ")
open(filename, "w")
file = open(filename)
file.write(text2)
choice3 = input("Read file? Y/N ")
if choice3 == 'Y' or choice3 == 'y':
print(file.read())
Your idea of issuing progress reports from your code is a good one, especially in the beginning stages. But it appears that you don't quite understand the difference between
print(open(new_file_name, "w"))
which is what your code actually does, and
print(f'open("{new_file_name}", "w")')
I believe the second of these is what you meant to do: it prints
open("myfile.txt", "w")
but what your actual code does is to (1) create an open file object for writing, then (2) print its type and memory location to the screen, and finally (3) throw it away.
So the first fix is to take out the print() calls, or at least reduce them to print("step 1") etc until you know how to do it properly.
The second fix is to not respond to the choice of Create by trying to read the file. If the user is creating the file then they are clearly not interested in the contents of any previous version. Your code responds to Create by reading the file, and that seems back-to-front to me, and in general programs should work the way that the average user, for example me, will think intuitive. Here is a correct way to do the Create bit:
choice = input("Open / Create file: ")
if choice == 'Create' or choice == 'create':
new_file_name = input("Create a name for the file: ")
with open(new_file_name, "w") as file2:
file2.write("This is stuff to go into the created file.\n")
else:
...
This asks for the name of the file, opens it for writing, then writes some stuff to it.

Login program from external text file

I'm having issues with a code where I have to get a user to type details about themselves, which saves to a text file. When the user tries to log in, it will check the text file for their details. Here is my code below. It works at first, where the user is granted access, but whenever I do a restart to my computer, or Python itself, it only grants the last user access. Some help would be appreciated, thank you:
This is what it looks like in the text file:
Adam16,adam123,Adam,Sunderland,16
Johnny18,johnny150,Johnny,Vane,18
This is the source code:
import csv
import sys
def register():
firstname = input("First name: ")
surname = input("Surname: ")
age = int(input("Age: "))
password = input("Password: ")
username = firstname[:3] + str(age)
with open("account.txt","a",newline="") as myfile:
writer = csv.writer(myfile)
writer.writerow([username,password,firstname,surname,age])
myfile.close()
menu()
def login():
user0 = input("Username: ")
pass0 = input("Password: ")
file = open("account.txt","r")
for line in file:
details = line.split(",")
if user0 == details[0] and pass0 == details[1]:
print("Correct!")
else:
print("Fail")
menu()
def menu():
selection = int(input("1 or 2: "))
if selection == 1:
register()
else:
login()
menu()
Your main problem is identation - your if user0 == details[0] and pass0 == details[1]: is on the same indentation as the for line in file:- meaning it is executed after the for-loop not inside it and for each details. You are currently only ever checking the last detail you parse from your file.
You can fix this by indenting it correctly.
This would then lead to multiple outputs - if your user is on line 100 it will print 99 fails and 1 correct - thats why I would put the printing outside the for loop. You can use break to abort the loop as soon as you found the correct user.
Changing your login to this will accomplish that:
def login():
user0 = input("Username: ")
pass0 = input("Password: ")
file = open("account.txt","r")
foundOne = False
for line in file:
details = line.split(",")
# execute Check on each line, not only on last line
if user0 == details[0] and pass0 == details[1]:
foundOne = True
break # this will instantly leave the for loop of line checkings
if foundOne == True:
print("Correct!")
else:
print("Fail")
menu()
I indented the if ... so it is done for each line instead of only once. I also set a status to avoid printing Fail for each checked line.
Make sure to use the correct username - it is a combination of firstname and age
Let me start by saying that I don't like to do complete rewrites if I can avoid it, I prefer to give the answer to the problem with as much of the original code in place.
The reason your code doesn't do what you expect is this bit:
for line in file:
details = line.split(",")
That only gives you the last line fed in as details is essentially overwritten every time the loop reads the next line in the file. You then come out of that for loop and check against details, so it only knows about the last line.
There's a number of ways you could go about this, I would suggest that the easiest is to use a dictionary instead of a list so that you can fill it up with the contents of the users file. You can also use csv.reader to read the csv file you created straight into a list without needing to split it first:
import csv
def login():
user_dict = {}
with open("account.txt", "r") as csvfile:
authfile = csv.reader(csvfile)
for line in authfile:
user_dict[line[0]] = line[1:]
user0 = input("Username: ")
if user_dict.get(user0):
pass0 = input("Password: ")
if user_dict.get(user0)[1] == pass0:
print("Correct!")
menu()
else:
print("Bad Password")
else:
print("Bad Username")
The first section creates the user dictionary and fills it with the details you've saved to file. First entry (username) is the key and the rest of the details are stored in a list under that key.
From there, we get the username and then do a get request on the dictionary to make sure the user exists (dict.get() will return None if it fails and won't raise an exception). If the user exists, we ask for their password and check it. If the password matches it prints out the affirmative answer and loads your menu function. If not, the user is notified that they've supplied a bad password.
I hope that all made sense. Let me know if you have any questions.
edit: I may have misread this one. It looks like everything leads back to the menu function no matter what. I do believe I've engaged in a bit of overkill.

How can I save to a .txt file without overwriting everything that was already in there? [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 7 years ago.
I'm making what is supposed to be just a very basic OS during my free time. However, I'm trying to make it so that you can have as many users as you want, but every time I make a new user, it deletes the old one. So far I have this:
def typer():
print("Start typing to get started. Unfortunately, you cannot currently save your files.")
typerCMD = input(" ")
CMDLine()
def CMDLine():
print("Hello, and welcome to your new operating system. Type 'help' to get started.")
cmd = input("~$: ")
if cmd == ("help"):
print("Use the 'leave' command to shut down the system. Use the 'type' command to start a text editor.")
cmdLvl2 = input("~$: ")
if cmdLvl2 == ("leave"):
quit()
if cmdLvl2 == ("type"):
typer()
def redirect():
signIn()
def mUserRedirect():
makeUser()
def PwordSignIn():
rPword = input("Password: ")
with open('passwords.txt', 'r') as f:
for line in f:
print(line)
if rPword == (line):
CMDLine()
else:
print("Incorrect password.")
signIn()
def signIn():
rUname = input("Username: ")
with open('usernames.txt', 'r') as f:
for line in f:
print(line)
if rUname == (line):
PwordSignIn()
else:
print("Username not found.")
mUserRedirect()
def makeUser():
nUname = input("New username: ")
nPword = input("Create a password for the user: ")
with open('usernames.txt', 'w') as f:
f.write(nUname)
with open('passwords.txt', 'w') as f:
f.write(nPword)
signIn()
print("Create a new user? (Y/N) ")
nUser = input("")
if nUser == ("N"):
signIn()
if nUser == ("n"):
signIn()
if nUser == ("Y"):
makeUser()
if nUser == ("y"):
makeUser()
So how can I write to the file without getting rid of everything that was already in there?
It depends on the "mode" you're using when opening your file. From the documentation:
'r' open for reading (default)
'w' open for writing, truncating the file first
'a' open for writing, appending to the end of the file if it exists
So all you have to do now is:
with open('usernames.txt', 'a') as f:
f.write(nUname)

Categories