open() in append mode is not behaving as expected - python-3.x

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

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)

Related

Trying to implement an user error message in python3

I have made a program that reads in a user expression and path file and then picks out each line from the users file that contains the expression. My code is as follows:
# Necessary imports
import os
# Variables
userExpression = [] # Variable for user expression
userFile = [] # Variable for user file
fileLines = [] # Variable for lines of text in the users file
lineNum = 0 # Variable for keeping track of line numbers
userExpression = " " + input("Please enter the expression you wise to find: ") + " " # Read in and store users expression
userFile = input("Enter the path of your file: ") # Read in and store file path of users file
myFile = open(userFile) # Opening user file
print(" ") # User to make output easier to read
print("HOORAY!! File found!")
print("File lines that include your expressions are found below: ")
print(" ") # User to make output easier to read
# Store each line of text into a list
for line in myFile:
lineNum += 1
if line.lower().find(userExpression) != -1:
fileLines.append("Line " + str(lineNum) + ": " + line.rstrip('\n'))
# Print out file text stored in list
for element in fileLines:
print(element)
myFile.close()
Last thing i want to try do is have an error message displayed if the user inputs an incorrect file path. Im new to python so honestly im not really sure where to even start.
You can solve this using a loop and a try/catch block:
while True:
userFile = input("Enter the path of your file: ") # Read in and store file path of users file
try:
myFile = open(userFile) # Opening user file
break
except:
print("Invalid file path!")
What the code does:
wait for user to tell program the file name
check if file can be opened
if file can be opened, exit the loop
if file cannot be opened, warn the user and go back to step 1
Edit: this solutions ensures Python can actually access the file, not only that it exists
You can use the os.path module to check if a file exists and if it’s a regular file (as opposed to a directory, for instance). First you import the module:
import os.path
from os import path
You use it as
if not path.exists(userFile):
# File does not exist
And to check if it’s a regular file:
if not path.isfile(userFile):
# Not a regular file
You can check more in this post.

Why can't i write to a file in python 3?

When I run,
Text = "Hello"
newFileName = (input("What would you like to name this file? "))
newFile = open(newFileName, 'w')
newFile.write(Text)
print("Saved as ", newFileName, "!")
It makes the file. However the file is empty. Does anyone know whats wrong here?
You have to close the file object newFile, otherwise the buffer that you are really writing to when you call newFile.write() might not get flushed to the actual file on disk. That is, add this line at the end:
newFile.close()
Python has a nice construct for dealing with this "setting up and tearing down" logic, known as context managers, used by the with statement. Using this, you can change your code to
Text = "Hello"
newFileName = input("What would you like to name this file? ")
with open(newFileName, 'w') as newFile:
newFile.write(Text)
print("Saved as ", newFileName, "!")
When the with block is done, the file is automatically closed, even if some error happens in the middle.

Content of file not printing

I am a beginner, learning programming using python 3.7. I am running a basic program to read content of a file after writing on it. But the print function won't print out the content of the file on the terminal. Can you please correct what mistake I am making here:
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
x = work.read()
print(x)
work.close()
After the write() completes, the file's object index needs to be moved to the beginning of the file
add work.seek(0) before the read() operation
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
work.seek(0)
x = work.read()
print(x)
work.close()
You can't actually read your spam variable since it is not a file.
Instead:
work = open("NewFile.txt", "w")
work.write(spam)
work.close()

Why is my code not appending correctly into an existing file?

When I run my code, there are no syntax errors, but it is not appending into the file. Basically, the user inputs their class and name (although this appears at the start of the program) and the program formulates a folder name and a file name - the file name being the user's name. The program then checks in the appropriate folder whether there is an existing file under the same name. If there isn't, the program creates a file in the correct folder and writes the user's score. The next time the same user runs the program, the file should be found. Python does output "File found", but the user's second score is not appended into the file. Any help on how to fix this?
All help is appreciated, thanks
Class_number = (input("Please enter your class: "))
score = (input("Please enter your score: "))
Folder = ("Class" + (Class_number))
File_name = (Name) + ".txt"
path = os.path.join("/Computing/a453/Task 3/",(Folder),(File_name))
if os.path.exists(path):
print("File found")
file = open((File_name), "a")
file.write((score) + "\n")
file.close()
else:
print("File not found. Creating file")
CompleteFile = os.path.join(Folder, File_name)
file = open(CompleteFile, "w")
file.write((score) + "\n")
file.close()
Short answer
You are checking if the file is present in a subfolder. If it is not present you create a new file in the desired folder and add the first score. If the file is present you are opening a different file! In the second case, the call to open just uses the filename without the folder (open(File_name, "a")) and not the whole path (open(CompleteFile, "w")).
Further Reading
Is there a special reason why you have to decide whether or not the file exists? Using open with mode a will create the file if it does not exist and append to it if it exists.
Note: open will not create missing folders for you!
Additionally, I would recommend to use Python's with statement (see this tutorial), as it will take care the file gets closed even if an exception is raised.
Combining everything said above your program would end up like this:
import os
name = "Test" # I had to come up with something
class_number = input("Please enter your class: ")
score = input("Please enter your score: ")
folder = "Class" + class_number
file_name = name + ".txt"
path = os.path.join(folder, file_name)
if os.path.exists(path):
print("File found")
else:
print("File not found. Creating file")
with open(path, "a") as txt_file:
txt_file.write(score + "\n")
In general, please check back with your Python reference. As someone told you in a comment, there are a lot of unnecessary parentheses and the style in naming your variables is not really consistent (have a look at Python's "official/recommended" naming conventions).
There are good online resources showing you the basics of Python. I personally enjoyed learning through Codecademy a lot (it's absolutely free).

Something's wrong with my Python code (complete beginner)

So I am completely new to Python and can't figure out what's wrong with my code.
I need to write a program that asks for the name of the existing text file and then of the other one, that doesn't necessarily need to exist. The task of the program is to take content of the first file, convert it to upper-case letters and paste to the second file. Then it should return the number of symbols used in the file(s).
The code is:
file1 = input("The name of the first text file: ")
file2 = input("The name of the second file: ")
f = open(file1)
file1content = f.read()
f.close
f2 = open(file2, "w")
file2content = f2.write(file1content.upper())
f2.close
print("There is ", len(str(file2content)), "symbols in the second file.")
I created two text files to check whether Python performs the operations correctly. Turns out the length of the file(s) is incorrect as there were 18 symbols in my file(s) and Python showed there were 2.
Could you please help me with this one?
Issues I see with your code:
close is a method, so you need to use the () operator otherwise f.close does not do what your think.
It is usually preferred in any case to use the with form of opening a file -- then it is close automatically at the end.
the write method does not return anything, so file2content = f2.write(file1content.upper()) is None
There is no reason the read the entire file contents in; just loop over each line if it is a text file.
(Not tested) but I would write your program like this:
file1 = input("The name of the first text file: ")
file2 = input("The name of the second file: ")
chars=0
with open(file1) as f, open(file2, 'w') as f2:
for line in f:
f2.write(line.upper())
chars+=len(line)
print("There are ", chars, "symbols in the second file.")
input() does not do what you expect, use raw_input() instead.

Resources