Trying to do a code but it does something different [duplicate] - python

This question already has answers here:
Why does my text file keep overwriting the data on it?
(3 answers)
Closed 2 years ago.
So, I did this python program and whenever I run it it says in the file "This is an update" and only one of the quotes I entered. Any help? Program below.
file_name = "my_quote.txt"
new_file = open(file_name, "w")
new_file.close()
def update_file(file_name,quote):
new_file = open(file_name, "w")
new_file.write("This is an update\n")
new_file.write(quote)
new_file.write("\n\n")
new_file.close()
for index in range(1,3):
quote = input("Enter your favorite quote:")
update_file(file_name, quote)
new_file = open(file_name, "r")
print(new_file.read())
new_file.close()

You're opening your file in w mode, which overwrites the file.
Use a for append mode, which, well, appends new content at the end.

You are writing over the current file as you are not opening the file in append mode.
If you change the open command to this instead:
file.open(file_path, 'a')
You will append the text instead of writing over the file.

Whenever you re-open a file, and use write it removes all content previously in the file and overwrites it. And since every time you call update_file you are re-opening it and writeing to it, only the last piece of info written in the last open will be kept (as all previous data was overwritten.
I think you want to use append mode when writing data to the file. See here for a list of all the modes, and their function.
Hope it helps!

Related

When I try and open/edit a .txt file in python, it deletes whatever is inside of the file. What is doing this? [duplicate]

This question already has answers here:
Confused by python file mode "w+" [duplicate]
(11 answers)
Closed 5 months ago.
Very short and simple. I am trying to create a highscore txt document for one of the games I'm making apart of a project. I want it to be able to keep the highest score ever reached in a text document so I can display it on the screen.
The file already exists, but whenever I load up the game, I get a "invalid literal for int() with base 10:" error. After looking, I realised this was because the file would delete anything inside of it when the program is started. Why is this? How can I fix it?
My code:
hisc = open("snakeScore.txt","w+")
highscore = hisc.read()
highscore_in_no = int(highscore)
if score>highscore_in_no:
hisc.replace(str(score))
highscore_in_no = score
Thats becuase You are using "w" when openning the file.
"w" Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
try using "r+" or "a"
From the documentation of Python3 for open:
r open for reading (default)
w open for writing, truncating the file first
'+' open for updating (reading and writing)
Then w+ will truncate the file before writing to it. You don't want that if you are required to read and store the content of it first.
Here's a working code, assuming that snakeScore.txt's content is a single line containing an integer, say "10":
score = 101
with open("snakeScore.txt", 'r+') as f:
highestscore = int(f.read())
if score > highestscore:
f.seek(0)
f.writelines(str(score))
The call to seek is needed in order to reset the pointer to the first line of the file, so we can rewrite the current line as opposed to adding a new one.

How do I clear all the contents of my file before I write on it? [duplicate]

This question already has answers here:
How to erase the file contents of text file in Python?
(13 answers)
Closed last year.
I would like to delete all the contents of my file first, then write on it. How do I do that with a simple file? `
fileHandle = open("file.txt","w")
fileHandle.write(randomVar)
fileHandle.close()
What you need is to open the file in a truncating mode. These are "w" and "w+". Your current code uses "w", so it should work fine!
In python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
https://stackoverflow.com/a/2769090/17773920
whenever using open(filename,'w') all the content of the data will be overwritten.
If you wish to add content to the file you should be using open(filename,'a').
In addition, I would recommend opening the file using
with open('filename','mode') as f: your code here
as it will provide context manager, making sure the file will closed when you are done with it.

How to fix "io.UnsupportedOperation: File not open for writing" Error? [duplicate]

This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 3 years ago.
In simplest terms, when i try to run a short amount of code to delete the contents of a file and then rewrite stuff to that file, it pulls that error. I'm trying to get a temperature reading from a com port using the filewrite from CoolTerm, perhaps it's the fact that the file is being used by CoolTerm as well, so I can't edit it, but I'm unsure.
I've tried multiple ways to delete the file information e.g the file.close(), and others, but none seem to work.
while True:
file = open("test.txt","r")
file.truncate()
x = file.read()
x = x.split("\n")
print(x[0])
print(x[1])
time.sleep(3)
I expect the console to output the contents of file but it doesn't. Something that gives me a similar result of what i want would be the Console just outputting the last two entries of the file, rather than having to delete all of it than rewriting it.
Modified to r+ mode is ok, I have tested.
with open('./install_cmd', 'r+') as f:
print(f'truncate ago:{f.read()}')
f.truncate(0)
print(f'truncate after:{f.read()}')

Using "with open() as file" method, how to write more than once? [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 6 years ago.
Usually to write a file, I would do the following:
the_file = open("somefile.txt","wb")
the_file.write("telperion")
but for some reason, iPython (Jupyter) is NOT writing the files. It's pretty weird, but the only way I could get it to work is if I write it this way:
with open('somefile.txt', "wb") as the_file:
the_file.write("durin's day\n")
with open('somefile.txt', "wb") as the_file:
the_file.write("legolas\n")
But obviously it's going to recreate the file object and rewrite it.
Why does the code in the first block not work? How could I make the second block work?
The w flag means "open for writing and truncate the file"; you'd probably want to open the file with the a flag which means "open the file for appending".
Also, it seems that you're using Python 2. You shouldn't be using the b flag, except in case when you're writing binary as opposed to plain text content. In Python 3 your code would produce an error.
Thus:
with open('somefile.txt', 'a') as the_file:
the_file.write("durin's day\n")
with open('somefile.txt', 'a') as the_file:
the_file.write("legolas\n")
As for the input not showing in the file using the filehandle = open('file', 'w'), it is because the file output is buffered - only a bigger chunk is written at a time. To ensure that the file is flushed at the end of a cell, you can use filehandle.flush() as the last statement.

Writing to file using Python [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 7 years ago.
I have a file called output.txt, which I want to write into from a few functions around the code, some of which are recursive.
Problem is, every time I write I need to open the file again and again and then everything I wrote before is deleted.
I am quite sure there is a solution, didn't find it in all questions asked here before..
def CutTable(Table, index_to_cut, atts, previousSv, allOfPrevSv):
print ('here we have:')
print atts
print index_to_cut
print Table[2]
tableColumn=0
beenHere = False
for key in atts:
with open("output.txt", "w") as f:
f.write(key)
and from another function:
def EntForAttribute(possibles,yesArr):
svs = dict()
for key in possibles:
svs[key]=(yesArr[key]/possibles[key])
for key in possibles:
with open("output.txt", "w") as f:
f.write(key)
All output I have is the last one written in one of the functions..
You need to change the second flag when opening the file:
w for only writing (an existing file with the same name will be
erased)
a opens the file for appending
Your code then should be:
with open("output.txt", "a") as f:
Every time you enter and exit the with open... block, you're reopening the file. As the other answers mention, you're overwriting the file each time. In addition to switching to an append, it's probably a good idea to swap your with and for loops so you're only opening the file once for each set of writes:
with open("output.txt", "a") as f:
for key in atts:
f.write(key)
I believe you need to open the file in append mode (as answered here: append to file in python) like this:
with open("output.txt", "a") as f:
## Write out
Short answer. change the 'w' in the file descriptor to 'a' for append.
with open("test.txt", "a") as myfile:
myfile.write("appended text")
this has already been answered in this thread.
How do you append to a file?

Categories

Resources