Created
October 26, 2022 01:48
-
-
Save ggorlen/e5886c0e0b10cb4bdc92ff9a5316032f to your computer and use it in GitHub Desktop.
Replace content in multiple files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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