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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -