mode = "a" stands for "to add", but I don't want to add a "YES", I want to erase the NO and write YES.
You want to erase the previous content of the file? Use 'w'
mode!
file = open("answer.txt", mode = "w", encoding = "utf-8")
file.write("YES")
file.close() # Now answer.txt contains only "YES"
To avoid calling that unestetic file.close
you can take advantage of _io.TextIOWrapper
's method __enter__
using a with
/as
block:
with open("answer.txt", 'w') as file:
file.write("YES")
You should know that 'a'
doesn't stand for "add" but for "append", and that there are other options that you can find in the documentation here
.
How do I edit a file, or a line in a file?
This second question is more complicated, you will have to do the following:
- Open the file
- Read the file
- Split the file in lines (or directly read it using
.readlines()
)
- Iterate through lines until you find the one you want to edit
- Edit the line
- Write to the file