osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


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