Sometimes, we want to edit specific line in text file in Python.
In this article, we’ll look at how to edit specific line in text file in Python.
How to edit specific line in text file in Python?
To edit specific line in text file in Python, we can call readlines
to read all the lines in the text file.
And then we call writelines
to write the new content into the same file after updating the file.
For instance, we write
with open('stats.txt', 'r') as file:
data = file.readlines()
data[1] = 'foo\n'
with open('stats.txt', 'w') as file:
file.writelines(data)
to call open
to open stats.txt.
Then we call readlines
to read in the whole file as a list.
Then we change 2nd line with
data[1] = 'foo\n'
Next, we open the same file with write permission with open
.
And then we call writelines
with data
to write the updated content into the file.
Conclusion
To edit specific line in text file in Python, we can call readlines
to read all the lines in the text file.
And then we call writelines
to write the new content into the same file after updating the file.