Python: Replace line clearing everything after line -


the following replace line function:

def replace_line(file_name, num, replaced):     f = open(file_name, 'r', encoding='utf-8')     lines = f.readlines()     lines[num] = replaced     f.close()     f = open(file_name, 'w', encoding='utf-8')     f.writelines(lines)     f.close() 

i using following line run code:

replace_line('store.txt', int(line), new) 

when run code, replaces line removes after line. example, if list:

to honest, i'm not sure wrong original function. tried redoing , seems work fine:

def replace_line(file_name, line_num, text):     open(filename, 'r+') f:         lines = f.read().splitlines()         lines[line_num] = text         f.seek(0)         f.writelines(lines)         f.truncate() 

please note overwrites entire file. if need handle large files or concerned memory usage, might want try approach.


Comments

Popular posts from this blog

Formatting string according to pattern without regex in php -

c - zlib and gdi32 with OpenSSL? -

java - inputmismatch exception -