Error code when trying to write to a text file - python

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.

Related

python readlines() function

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)

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.

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)

What is a " AttributeError: '_io.TextIOWrapper' object has no attribute 'replace' " in python?

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)

Categories