how to replace first line of a textfile python

Solutions on MaxInterview for how to replace first line of a textfile python by the best coders in the world

showing results for - "how to replace first line of a textfile python"
Gwendoline
05 Nov 2017
1with open("test.txt") as f:
2    lines = f.readlines()
3
4lines # ['This is the first line.\n', 'This is the second line.\n']
5
6lines[0] = "This is the line that's replaced.\n"
7
8lines # ["This is the line that's replaced.\n", 'This is the second line.\n']
9
10with open("test.txt", "w") as f:
11    f.writelines(lines)