Can't Append to the File - python

I'm trying to write this program where if the user opens an existing file, they have the option to either read, start over, or append to it, but the append option isn't working. Why is that?
from sys import argv
file = input("Please open a file: ")
try:
file = open(file, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "a":
print(file.read())
elif choice in "b":
print("What would you like to write?")
file.write(input())
elif choice in "c":
file = open(file, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())```

The problem with your code is that you are assigning the variable file to the input of the user in input("Please open a file: "), but right after this you assign it to be the txt file in file = open(file, "r+").
So, when you write file = open(file, "a"), the compiler is reading file not as the user input, but the opened txt file.
What you should do is to give different names to the different variables
from sys import argv
filename = input("Please open a file: ")
try:
file = open(filename, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "aA":
print(file.read())
elif choice in "bB":
print("What would you like to write?")
file.write(input())
elif choice in "cC":
file.close()
file = open(filename, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())
UPDATE
As OneLiner said in the comments, you should always close the files after opening them. This can be easily done by using, as he said, with open(filename, "a") as file:. Besides that, I noticed two more things.
First, you shouldn't use except alone, because if I try, for example, to press ctrl+c, it will fall into this exception. What you should write instead is except FileNotFoundError, so that if there is no such file, this exception will be raised.
The second thing I noticed is that you are using the name file as the name of a variable. The problem is that file is already being used in python for another thing, so it would be better to use another name. In that case the code would be:
from sys import argv
filename = input("Please open a file: ")
try:
with open(filename, "r+") as file_txt:
pass
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice == "a":
with open(filename, "r") as file_txt:
print(file_txt.read())
elif choice == "b":
content = input("What would you like to write?\n")
with open(filename, "w") as file_txt:
file_txt.write(content)
elif choice == "c":
with open(filename, "a") as file_txt:
content = input("What would you like to write?\n")
file_txt.write(content)
except FileNotFoundError:
print("This is a new file.\n")
with open(filename, "w") as file_txt:
content = input("What would you like to save in this file?\n")
file_txt.write(content)

Using "r+" allows you to read and write, but the pointer is at the beginning, meaning that "appending" doesn't actually exist. If I'm not mistaken, there's no way to open a file for reading, writing, and appending, because there's no way to move the pointer along the file.
To get around this, I would suggest opening the file separately in each if clause.
If the person wants to read the file, then open it using "r".
If the person wants to write to the file, then open it using "w", and if the person wants to append to it, then open it using "a". More options, such as combinations of two can be found here.
The code:
try:
#removed:
#file = open(file, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "a":
file = open(file, "r")
print(file.read())
elif choice in "b":
file = open(file, "w")
print("What would you like to write?")
file.write(input())
elif choice in "c":
file = open(file, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())

Related

Unable to write variables (input) to text file

I'm currently writing a simple text editor in python 3.8, I am unable to write the contents of the user input into a file though. When I open the text file in notepad++ a message pops up saying - "This file has been modified by another program, would you like to reload it?". I've tried writing the input to the file as an array but that does not work.
loop = True
#Getting file name
filename = input('Filename(Include file extensions) : ')
#Getting What To Write To File
while loop == True:
text = input('>> ')
if "EXIT" in text:
loop = False
while loop == False:
#writing to file
saveFile = open(filename, 'w')
saveFile.write(text)
saveFile.close()
Your loop structure is a bit off. There is no need for using "flag" variables. A more pythonic way is while True: ... break. So your code should look more like this:
#Getting file name
filename = input('Filename(Include file extensions) : ')
#Getting What To Write To File
while True:
text = input('>> ')
if "EXIT" in text:
break
#writing to file
with open(filename, 'w') as saveFile:
saveFile.write(text)
Of course this will only write the last input with the EXIT, so you might want to make text a list or a queue to perform as a buffer, or just dump directly to the file:
#Getting file name
filename = input('Filename(Include file extensions) : ')
#Getting What To Write To File
with open(filename, 'w') as saveFile:
while True:
text = input('>> ')
saveFile.write(text)
if "EXIT" in text:
break

Python code isnt printing contents of txt?

elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")

Python file read and save

I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.
My code:
while True:
print("-------------")
name=input("Name: ")
age=input ("Age: ")
contInput=input("Continue Input? (y/n) ")
fp.open("test.txt", "a")
fp.write(name+","+age+"\n")
if contInput=="n":
fp.close()
break
else:
continue
with open("test.txt", "r") as fp:
rd = fp.read().split('\n')
????
fp.close()
so I just confuse about file read. I want to print my saved data like below.
name [tab] age
but after used split method, rd type is list.
Can I divide name & age as each items?
fp.open("test.txt", "a")
At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?
You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.
fp.write(name+","+"age"+"\n")
This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")
Try this for your input loop:
with open("test.txt", "r") as fp:
for line in fp:
data = line.split(",")
name = data[0]
age = data[1]

Try to save and write to a file

while True: # Saving a file in txt file
print("Would you like to save the latest generation? ('y' to save): ")
saveInput = input()
if saveInput == 'y' or saveInput == 'Y':
print("Enter destination file name: ")
fileName = input()
try:
open(fileName, "r")
close(fileName)
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()
if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')
elif confirm == 'y':
open(confirm, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
except:
break
This is what i got so far, I'm trying to first read a file take the data from that, and run it through my program and at the end ask if they want to save it, if the file exists ask if they want to overwrite it, and if not create a new one but when i try it skips after you input the destination name like so:
Output
Enter input file name:
g.txt
How many new generations would you like to print?
4
Would you like to save the latest generation? ('y' to save):
y
Enter destination file name:
g.txt
>>>
Can someone help me out? I've been stuck on it for a while
In the code part where you "try" to open the file, the file doesn't exist yet, so it gets to the "except" part (break) and the program terminates.
try:
open(fileName, "r")
close(fileName)
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()
if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')
elif confirm == 'y':
open(confirm, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
except:
break
Replace it with os.path.isfile(fileName)
if os.path.isfile(fileName):
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()
if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')
elif confirm == 'y':
open(**fileName**, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
# if fileName doesn't exist, create a new file and write the line to it.
else:
open(**fileName**, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
When you open the file, you need to create a variable to hold that file and write to it.
Right now, you are trying to call writelines on a string, not a file when you do this: confirm2.writelines(new_glider)
Here's how to write to a file properly:
with open(confirm, 'w') as f:
f.writelines(new_glider)

'NameError 'test' not defined. where am I going wrong?

I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.

Categories

Resources