Skip to content

Instantly share code, notes, and snippets.

@ialex32x
Created June 1, 2017 05:58
Show Gist options
  • Save ialex32x/b182ce9e236c38e22e95d06fdfe67277 to your computer and use it in GitHub Desktop.
Save ialex32x/b182ce9e236c38e22e95d06fdfe67277 to your computer and use it in GitHub Desktop.
replace all occurence
filename_in = "sourcefile.name"
filename_out = "destinationfile.name"
fin = open(filename_in, "r")
fout = open(filename_out, "w")
original_word = "WORD"
replace_by = "DROW"
match_buffer = ""
replace_count = 0
try:
while True:
ch = fin.read(1)
if not ch:
break
cc = original_word[len(match_buffer)]
if ch == cc:
match_buffer = match_buffer + cc
if len(match_buffer) == len(original_word):
print("replaced %d" % (replace_count))
replace_count = replace_count + 1
match_buffer = ""
fout.write(replace_by)
else:
if len(match_buffer) != 0:
fout.write(match_buffer)
fout.write(ch)
match_buffer = ""
finally:
fin.close()
fout.close()
print("total replace: %d" % (replace_count))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment