how to replace first line of a textfile python 1

how to replace first line of a textfile python

with open("test.txt") as f:
    lines = f.readlines()

lines # ['This is the first line.\n', 'This is the second line.\n']

lines[0] = "This is the line that's replaced.\n"

lines # ["This is the line that's replaced.\n", 'This is the second line.\n']

with open("test.txt", "w") as f:
    f.writelines(lines)

Here is what the above code is Doing:
1. Open the file in read mode.
2. Read the lines into a list.
3. Modify the first line.
4. Open the file in write mode.
5. Write the modified lines to the file.

Similar Posts