Skip to content

Instantly share code, notes, and snippets.

@MichaelStett
Created May 16, 2023 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelStett/e2071e764a81b8f43cb64fcc5234fb5f to your computer and use it in GitHub Desktop.
Save MichaelStett/e2071e764a81b8f43cb64fcc5234fb5f to your computer and use it in GitHub Desktop.
Replace text
import os
path = ""
fileType = ".xml"
dictionary = {
"oldvalue": "newvalue",
}
modified = False
for dname, dirs, files in os.walk(os.path.normpath(path)):
for fname in files:
fpath = os.path.join(dname, fname)
if fpath.endswith(fileType) == True:
with open(fpath, "r", encoding="ISO-8859-1") as f:
s = f.read()
for key in dictionary:
if key in s:
s = s.replace(key, dictionary[key])
modified = True
if modified:
with open(fpath, "w", encoding="ISO-8859-1") as f:
f.write(s)
modified = False
else:
print(f"{fpath} was not modified.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment