Skip to content

Instantly share code, notes, and snippets.

@AntumDeluge
Created January 10, 2020 05:02
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 AntumDeluge/67077b40dd8bcb900d6cf1c0cc403901 to your computer and use it in GitHub Desktop.
Save AntumDeluge/67077b40dd8bcb900d6cf1c0cc403901 to your computer and use it in GitHub Desktop.
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