how to replace line on particular line in file[no need to write it back whole file again]

Iranna Mathapati iranna.gani28 at gmail.com
Thu Oct 11 05:44:49 EDT 2018


Hi Team,

How to replace particular line text with  new text on a file
i have below code but its writing whole code.

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)  <<<<< *writing back whole file instead of
particular line*
    out.close()
replace_line('stats.txt', 0, 'good')


Thanks,
Iranna M



More information about the Python-list mailing list