'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?
Solution 1:[1]
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")
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sharim Iqbal |
| Solution 2 |
