The Python script implements the formatting of the css file
- 2020-05-05 11:28:01
- OfStack
Recently, I have studied css, and it is necessary to analyze other people's web pages on the Internet. However, the css files of many websites are written in one line or no line break, which seems extremely painful, so write a script to convert them into a more readable format. Here's the script:
import string, sys
import re, StringIO
TAB=4
def format(ss):
f = open (ss, "r")
data = f.read()
f.close()
dlen = len(data)
i = 0
buf = StringIO.StringIO()
start = 0
while i < dlen:
if data[i] == '{':
buf.write(data[start:i] + ' { ')
i = i + 1
start = i
elif data[i] == '}':
last = string.strip(data[start:i])
if last:
buf.write(' '*TAB + last + ';')
buf.write(' } ')
i = i + 1
start = i
elif data[i] == ';':
line = string.strip(data[start:i])
buf.write(' '*TAB + line + '; ')
i = i + 1
start = i
else:
i = i + 1
buf.write(data[start:i+1])
return buf.getvalue()
if __name__ == '__main__':
if len(sys.argv) == 1:
print 'usage: cssformat.py filename'
sys.exit()
ret = format(sys.argv[1])
print ret
How to use:
python cssformat.py filename > to be converted Saved file
after conversion