Skip to content

Instantly share code, notes, and snippets.

@alexanderfast
Created August 19, 2016 14:55
Show Gist options
  • Save alexanderfast/4da24230e31206650bff2f970a7093f3 to your computer and use it in GitHub Desktop.
Save alexanderfast/4da24230e31206650bff2f970a7093f3 to your computer and use it in GitHub Desktop.
Python script to trim trailing white space recursively for all files matching a specified file mask regex.
#
# Usage:
#
# python trimwhitespace.py . .*\.js$
#
import argparse
import os
import re
parser = argparse.ArgumentParser(description='Trims trailing whitespace.')
parser.add_argument('root_directory', type=str, default='.', nargs='?',
help='directory to run the script in')
parser.add_argument('file_mask_regex', default=".*", nargs='?',
help='file name mask regex')
args = parser.parse_args()
file_mask_regex = re.compile(args.file_mask_regex)
print('Starting whitespace trimming. \
directory {0}, file mask {1}'.format(args.root_directory, 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:
file_contents = ''
with open(file_path) as f:
file_contents = "\n".join((l.rstrip() for l in f.readlines())) + "\n"
print('Trimming whitespace in {0}'.format(file_path))
with open(file_path, "w") as f:
f.write(file_contents)
print('Done')
@alexanderfast
Copy link
Author

Based upon tabs2spaces.py.

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