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.
Related
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)
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.
I am programming a dice game that only allows authenticated users to play, I have a method of appending and creating a password to a file. But I cannot search for a specific password that the user enters. My main goal for the section of the program is to create an 'if' statement that checks if the computer has found the specific password or not.
I am new to using the find statement, I have looked through many questions and examples over the past few days to no avail - I cannot get my head around how it would work with my code.
def Lock_Screen():
print("Welcome")
print("Log in(1) or Sign up(2)")
User_Choice = input("")
if User_Choice == "1":
print("Input your three-digit code:")
UserInput = input(str(""))
x = open("PasswordList.txt" , "r")
x.find(Userinput)
if x.find(UserInput):
Start_Screen()
elif User_Choice == "2":
Password = random.randint(100,999)
f = open("PasswordList.txt" , "a+")
x = open("PasswordList.txt" , "r")
PasswordList = x.read()
while Password == PasswordList:
Password = random.randint(100,999)
print("This is your password: " , Password)
f = open("PasswordList.txt" , "a+")
f.write(str(Password))
f.close()
Lock_Screen()
else:
print("That was not a valid answer")
Lock_Screen()
Lock_Screen()
The .find statement is suppose to find the variable but it just returns with an error message.
Open files do not have a method named find. You seem to be looking for
Userinput = input("Input your three-digit code: ")
with open(filename) as x:
for line in x:
if line.rstrip('\n') == Userinput:
print("password correct")
break
else:
print("password not found")
The with context manager takes care of closing the open file handle when you are done.
I am making a program which has a login; it checks the input against the user's input. However, it won't accept that they have entered the correct password, even when it is correct:
for i in range(5):
existingUsername = input("What is your user name?")
if existingUsername in open('logins.txt').read():
with open("logins.txt", "r") as myFile:
for num, line in enumerate(myFile, 1):
if existingUsername in line:
passwordLine = num + 1
passwordAttempt = input(str("What is your password?"))
passwordText = linecache.getline("logins.txt", passwordLine)
if passwordAttempt == passwordText:
print("That is correct")
quizSelection()
break
else:
print("That doesn't seem to match. Please try again")
The text file it references only has Har16 and Google in it, on separate lines with Har16 at the top
When you run passwordText = linecache.getline("logins.txt", passwordLine), if your file has multiple lines, it may return the string with \n at the end.
print (
""" Welcome to the code breaker game!
In this game you will have to change symbols into letters in order to decipher secret words.
0 - instructions
1 - start
2 - clues
3 - check your answers
4 - quit
""")
choice = input(" choice : ")
if choice == ("0"):
text_file = open ("instructions.txt","r")
print (text_file.read())
text_file.close()
elif choice =="1":
text_file = open ("words.txt","r")
contents = text_file
print (text_file.read())
text_file.close()
a = input("Please enter a symbol ")
b = input("Please enter a letter ")
newcontents = contents.replace(a,b)
contents = newcontents
print(contents,"\n")
text_file.close
elif choice == "2":
text_file = open ("clues.txt","r")
print (text_file.read())
text_file.close()
elif choice == "3":
text_file = open ("solved.txt","r")
print (text_file.read())
text_file.close()
elif choice == "4":
quit
So basically I'm doing a computer science project and my task is to make a decoding game by substituting symbols to letters but I get this error for when I try to make the part of the code which actually changes symbols into letters.
Also is there any way to make this loop (not using while loops as they are quite complicated)? I basically want the code to show me the A and B when I run the program and for me after choosing any option to be able to choose a different option. (Eg I press 0 for instructions and then be able to choose a different option such as start game).
This part of your code:
text_file = open ("words.txt","r")
contents = text_file
print (text_file.read())
text_file.close()
makes no sense. You are assigning the file object (not the file's contents) to contents. You then print the contents, but don't assign them to anything. I think what you want is:
with open("words.txt") as text_file:
contents = text_file.read()
print(contents)