My first write to the file needs to overwrite it, then my next ones need to append to it. But There is no way to know what write will be first. My writes are in conditional statements. Here is what I have:
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.strict = False
self.indent = " "
self.pos = 0
self.output_file = 'output_sass.txt'
def handle_starttag(self, tag, attrs):
if attrs != []:
for attr in attrs:
if ('id' in attr):
id = attr.index('id')
with open(self.output_file, 'w') as the_file:
the_file.writelines(self.indent * self.getpos()[1] + '#' + attr[id+1] + ' {' +'\n')
## print (self.indent * self.getpos()[1] + "#" + attr[id+1] + " {")
self.pos = self.getpos()[1]
break
elif ('class' in attr):
clas = attr.index('class')
with open(self.output_file, 'w') as the_file:
the_file.writelines(self.indent * self.getpos()[1] + "." + attr[clas+1] + " {"+'\n')
## print (self.indent * self.getpos()[1] + "." + attr[clas+1] + " {")
self.pos = self.getpos()[1]
break
else:
with open(self.output_file, 'w') as the_file:
the_file.writelines(self.indent * self.getpos()[1] + tag + " {"+'\n')
## print (self.indent * self.getpos()[1] + tag + " {")
self.pos = self.getpos()[1]
break
else:
with open(self.output_file, 'w') as the_file:
the_file.writelines(self.indent * self.getpos()[1] + tag + " {"+'\n')
## print (self.indent * self.getpos()[1] + tag + " {")
self.pos = self.getpos()[1]
def handle_endtag(self, tag):
with open(self.output_file, 'w') as the_file:
the_file.writelines(self.indent * self.pos + "}"+'\n')
## print(self.indent * self.pos + "}")