Skip to content

Instantly share code, notes, and snippets.

@stucka
Created June 10, 2016 16:41
Show Gist options
  • Save stucka/48179a6defbdc53690254f15a9639cbc to your computer and use it in GitHub Desktop.
Save stucka/48179a6defbdc53690254f15a9639cbc to your computer and use it in GitHub Desktop.
Optimize yer CSS through Python
def optimize_css(directory):
import os
from csscompressor import compress
print("\tOptimizing CSS in " + directory)
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
# Now we have a list of all CSS files in directory.
for source in file_paths:
if source[-4:] == ".css" and source[-8:-4] != "-min": # if we have a CSS file and it's not already minimized ...
with open(source, "r") as sourcefilehandle:
rawcss = sourcefilehandle.read()
target = source[:-4] + "-min.css" # New ending to the filename
with open(target, "w") as targetfilehandle:
targetfilehandle.write(compress(rawcss))
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment