Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple script for cleaning up whitespace in text/source files.
#!/usr/bin/env python
# A simple script for cleaning up whitespace in text/source files.
#
# Licensing: CC0
# The author hereby relinqueshes any copyright claim to this script
# & dedicates it to the public domain.
#
# TODO:
# - add help & usage information
import os, sys
from platform import system
win32 = (system().lower() == "windows")
args = sys.argv[1:]
if not args:
print("ERROR: Directory argument required. Exiting ...")
sys.exit(1)
def formatPath(path):
if win32:
path = path.replace("/", "\\").replace("\\\\", "\\")
else:
path = path.replace("\\", "/").replace("//", "/")
return path
dir = formatPath(args[0])
filetype = None
if len(args) > 1:
filetype = args[1]
if not os.path.isdir(dir):
print("ERROR: \"{}\" is not a directory. Exiting ...".format(dir))
sys.exit(1)
if not filetype:
print("ERROR: Filename extension required. Exiting ...")
sys.exit(1)
def cleanWhitespace(filepath):
if not os.path.isfile(filepath):
print("ERROR: \"{}\" is not a file. Exiting ...".format(filepath))
sys.exit(1)
BUFFER = open(filepath, "r", encoding="utf-8")
lines = BUFFER.read().split("\n")
BUFFER.close()
cleaned_lines = []
idx = 0
while idx < len(lines):
cleaned_lines.append(lines[idx].rstrip(" \t"))
idx += 1
# Remove extra newlines at end of file
cleaned_text = "{}\n".format("\n".join(cleaned_lines).rstrip("\n"))
if cleaned_text != "\n".join(lines):
# Destroys old text
BUFFER = open(filepath, "w", encoding="utf-8", newline="\n")
BUFFER.write(cleaned_text)
BUFFER.close()
print("Cleaned: {}".format(filepath))
for ROOT, DIRS, FILES in os.walk(dir):
for F in FILES:
if F.endswith(".{}".format(filetype)):
filepath = formatPath("{}/{}".format(ROOT, F))
cleanWhitespace(filepath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.