Skip to content

Instantly share code, notes, and snippets.

@Nanguage
Forked from amoilanen/tabs2spaces.py
Last active July 17, 2018 03:41
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 Nanguage/0781ff4cd6109042aff8020206c6add9 to your computer and use it in GitHub Desktop.
Save Nanguage/0781ff4cd6109042aff8020206c6add9 to your computer and use it in GitHub Desktop.
Python script to replace tabs with spaces recursively for all files matching a specified file mask regex, the number of spaces if configurable
USAGE = '''
Usage example:
python tabs2spaces.py . 4 ".*\.py$"
'''
import io
import argparse
import os
import re
parser = argparse.ArgumentParser(description='Replace tabs with spaces.'+USAGE)
parser.add_argument('root_directory', type=str,
help='directory to run the script in')
parser.add_argument('spaces_for_tab', type=int, default=4, nargs='?',
help='number of spaces for one tab')
parser.add_argument('file_mask_regex', default=".*", nargs='?',
help='file name mask regex')
parser.add_argument("--head-only", action='store_true', default=True,
help='only change the tab in the head of each line.')
args = parser.parse_args()
file_mask_regex = re.compile(args.file_mask_regex)
replacement_spaces = ' ' * args.spaces_for_tab
print('Starting tab replacement. \
directory {0}, spaces number {1}, file mask {2}'.format(args.root_directory, args.spaces_for_tab, args.file_mask_regex))
found_files = []
for path, subdirs, files in os.walk(args.root_directory):
for name in files:
found_files.append(os.path.join(path, name));
matched_files = [name for name in found_files if file_mask_regex.match(name)]
for file_path in matched_files:
print('Replacing tabs in {0}'.format(file_path))
file_contents = ''
with open(file_path) as f:
file_contents = f.read()
if args.head_only:
file_lines = file_contents.split("\n")
file_lines_out = []
for line in file_lines:
if not line.startswith("\t"):
file_lines_out.append(line)
continue
else:
head_tabs = re.findall("^\t+", line)[0]
head_spaces = head_tabs.replace("\t", replacement_spaces)
line = re.sub('^'+head_tabs, head_spaces, line)
file_lines_out.append(line)
file_contents = "\n".join(file_lines_out)
else:
file_contents = re.sub('\t', replacement_spaces, file_contents)
with open(file_path, "w") as f:
f.write(file_contents)
print('Done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment