Skip to content

Instantly share code, notes, and snippets.

@thewh1teagle
Created December 27, 2020 02:10
Show Gist options
  • Select an option

  • Save thewh1teagle/908fff285bbac0acde03f7e0aeb59e2a to your computer and use it in GitHub Desktop.

Select an option

Save thewh1teagle/908fff285bbac0acde03f7e0aeb59e2a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Convert camelCase file into snake_case file using python.
"""
import re
import argparse
import sys
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
def camelToSnake(s):
"""
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert camelCase file into snake_case file using python.')
parser.add_argument('-i', type=str, required=True,
help='input file')
parser.add_argument('-o', required=True,
help='out file')
args = parser.parse_args()
try:
with open(args.i, 'r') as f:
content = f.read()
new_content = camelToSnake(content)
except FileNotFoundError:
print("File {} not found.".format(args.i))
sys.exit(1)
with open(args.o, 'w') as f:
f.write(new_content)
@thewh1teagle
Copy link
Author

Quick Usage:

python3 <(curl -s https://gist.githubusercontent.com/thewh1teagle/908fff285bbac0acde03f7e0aeb59e2a/raw/c310ebb413440721cef68723f76d34593e6a9938/camel2snake.py) \
-i infile -o outfile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment