Skip to content

Instantly share code, notes, and snippets.

@almarklein
Last active May 24, 2021 15:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save almarklein/8e46d3449991898561803255ea45d572 to your computer and use it in GitHub Desktop.
Save almarklein/8e46d3449991898561803255ea45d572 to your computer and use it in GitHub Desktop.
Trim trailing whitespace in Python files
import os
def trim_py_files(*directories):
"""Remove trailing whitespace on all .py files in the given directories.
"""
nchanged = 0
for directory in directories:
for root, dirs, files in os.walk(directory):
for fname in files:
filename = os.path.join(root, fname)
if fname.endswith('.py'):
with open(filename, 'rb') as f:
code1 = f.read().decode()
lines = [line.rstrip() for line in code1.splitlines()]
while lines and not lines[-1]:
lines.pop(-1)
lines.append('') # always end with a newline
code2 = '\n'.join(lines)
if code1 != code2:
nchanged += 1
print(' Removing trailing whitespace on', filename)
with open(filename, 'wb') as f:
f.write(code2.encode())
print('Removed trailing whitespace on {} files.'.format(nchanged))
if __name__ == '__main__':
trim_py_files(os.path.dirname(__file__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment