1

I have a file called "answer" with "NO" written in it. But in a certain moment of my code I want to change it to "YES".

Doing this:

file = open("answer.txt", mode="r", encoding="utf-8")
read = file.read()
print(read)

The output is: NO

I know mode = "a" stands for "to add", but I don't want to add a "YES", I want to erase the NO and write YES.

How do I edit a file, or a line in a file?

martineau
  • 119,623
  • 25
  • 170
  • 301
andreadebe
  • 27
  • 3

2 Answers2

2

Use with syntax you don't need to close the file.


with open("answer.txt", mode = "w", encoding = "utf-8") as file:
    file.write("YES")
codester_09
  • 5,622
  • 2
  • 5
  • 27
1

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
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28