I've looking for here and there how to replace multiple lines in file with new ones but my code just add a line to very end of file. How to replace old line with new one in proper place ?
path = /path/to/file
new_line = ''
f = open(path,'r+b')
f_content = f.readlines()
line = f_content[63]
newline = line.replace(line, new_line)
f.write(newline)
f.close()
edited: path = /path/to/file path_new = path+".tmp" new_line = "" with open(path,'r') as inf, open(path_new, 'w') as outf: for num, line in enumerate(inf): if num == 64: newline = line.replace(line, new_line) outf.write(newline) else: outf.write(line) new_file = os.rename(path_new, path)
f_content.seek(n), where n is the index of line .seek(0)takes to start of file.