Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Created October 26, 2022 01:48
Show Gist options
  • Select an option

  • Save ggorlen/e5886c0e0b10cb4bdc92ff9a5316032f to your computer and use it in GitHub Desktop.

Select an option

Save ggorlen/e5886c0e0b10cb4bdc92ff9a5316032f to your computer and use it in GitHub Desktop.
Replace content in multiple files
import fnmatch
import os
import re
for directory, dirnames, filenames in os.walk("."):
for f in fnmatch.filter(filenames, "*.yml"):
path = os.path.join(directory, f)
with open(path) as file:
content = file.read()
####
pat = r"(?<= {8}- input_arguments:\n) {10}- type: \w+\n {11}"
content = re.sub(pat, " " * 10 + "-", content)
####
with open(path, "w") as file:
file.write(content)
'''
import os
import re
import shutil
import tempfile
for directory, dirnames, filenames in os.walk("."):
for f in filenames:
if not f.endswith(".yml"):
continue
orig_path = os.path.join(directory, f)
with open(orig_path) as orig:
content = orig.read()
####
pat = r"(?<= {8}- input_arguments:\n) {10}- type: \w+\n {11}"
content = re.sub(pat, " " * 10 + "-", content)
####
with tempfile.NamedTemporaryFile() as temp:
temp.write(content.encode("utf-8"))
temp.flush()
shutil.copy2(temp.name, orig_path)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment