andreadebe
andreadebe

Reputation: 25

How to programmatically edit a text file?

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?

Upvotes: 0

Views: 2813

Answers (2)

Sharim09
Sharim09

Reputation: 6214

You can use mode='w' to write in file, mode='w' will first erase the content if exists or create new file if not exists and then write the text you want to write.

And, use with syntax, so you don't need to close the file.


with open("answer.txt", mode = "w", encoding = "utf-8") as file:
    file.write("YES")

Upvotes: 1

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

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

Upvotes: 1

Related Questions