I have a text file which consists of many lines of text.
I would like to replace only the first line of a text file using python v3.6 regardless of the contents. I do not need to do a line-by-line search and replace the line accordingly. No duplication with question Search and replace a line in a file in Python
Here is my code;
import fileinput
file = open("test.txt", "r+")
file.seek(0)
file.write("My first line")
file.close()
The code works partially. If the original first line has string longer than "My first line"
, the excess sub-string still remains. To be clearer, if original line is "XXXXXXXXXXXXXXXXXXXXXXXXX"
, then the output will be "My first lineXXXXXXXXXXXXXX"
. I want the output to be only "My first line"
. Is there a better way to implement the code?