how do i overwrite to a specific part of a text file in python -
for example if in text file have,
explosion,bomb,duck jim,sam,daniel
and wanted change daniel in file, nothing else affected. how achieve without overwriting whole file.
you can use fileinput
import fileinput fileinput.fileinput(filetosearch, inplace=true, backup='.bak') file: line in file: print(line.replace(texttosearch, texttoreplace), end='') #testtosearch:- daniel #texttoreplace:- newname
or if want keep more simple, operation in reading 1 file , writing replaced content in second file. , overrite it!
f1 = open('orgfile.txt', 'r') f2 = open('orgfilerep.txt', 'w') line in f1: f2.write(line.replace('texttosearch', 'texttoreplace'), end=' ') f1.close() f2.close()
Comments
Post a Comment