Reputation: 61
i am trying to create a program that asks to the user what they want to do to a file read/append/delete the file.
FileName = open(input("Enter file name: "))
ReadFile = FileName.read()
Decision = input("Do you want to read/delete/append to the file?: ")
if Decision == "read":
print(ReadFile)
FileName.close()
elif Decision == "append":
Append = input("Type what you want to add: ")
with open("FileName","a") as file:
file.write(Append)
but when i check the file the it doesn't append it
Upvotes: 0
Views: 962
Reputation: 3450
This is happening because you're not actually opening the same file. You're asking the user for input to specify a file's location for reading that file, but should they choose to "append" the file, you have them append to a file that has nothing to do with the file they specified. You're having the user append a file called "FileName"
. You have hard coded that string as the file's location when the user chooses to "append".
Here, FileName
is not a string representing the file's location. This is an object representing the file.
FileName = open(input("Enter file name: "))
You had the user enter a string to the file's path, but you didn't store that string value. You used that value to open()
a file up for reading.
Here, you're opening a file called "FileName"
in what is likely the directory python started in, since there's no path visible here.
with open("FileName","a") as file:
file.write(Append)
Go look in your starting directory and see if you've created a new file called "FileName"
.
Keep in mind, if you open a file with mode="a"
, and that file does not exist, a new file will be created.
https://docs.python.org/3/library/functions.html#open
I would also like to use this moment to inform you about PEP8, Python's styling guide. It's not law, but following it will help other Python programmers help you quicker.
With that said, consider making your code snippet look more like the following code:
filename = input("Enter file name: ")
decision = input("Do you want to read/delete/append to the file?: ")
if decision == "read":
with open(filename) as file:
print(file.read())
elif decision == "append":
append = input("Type what you want to add: ")
with open(filename, "a") as file:
file.write(append)
Upvotes: 1