Skip to content

Instantly share code, notes, and snippets.

@mohammedri
Created February 23, 2020 21:28
Show Gist options
  • Save mohammedri/0aff149bb5b24017fd5fc48b2b0abd1d to your computer and use it in GitHub Desktop.
Save mohammedri/0aff149bb5b24017fd5fc48b2b0abd1d to your computer and use it in GitHub Desktop.
Small Python script to search and replace a set of Python files for any multiline regex
#!/usr/bin/env python3
import fileinput
import sys
import re
import os
rootdir = os.getcwd()
extensions = ('.py')
def replaceFile(filename, searchExp, replaceExp):
with open(filename, 'r') as f:
content = f.read()
content_new = re.sub(searchExp, replaceExp, content, 0, re.DOTALL)
with open(filename, "w") as f:
f.write(content_new)
regex = r'\"\"\"\nCopyright \(C\) MyCompany Corp.*\d\d\d\d\n\"\"\"\n'
for subdir, dirs, files in os.walk(rootdir):
# Ignore hidden files and folders
files = [f for f in files if not f[0] == '.']
dirs[:] = [d for d in dirs if not d[0] == '.']
for file in files:
ext = os.path.splitext(file)[-1].lower()
if ext in extensions:
replaceFile(os.path.join(subdir, file), regex, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment