ファイルへの最初の書き込みではファイルを上書きする必要があり、次にファイルに追加する必要があります。しかし、どの書き込みが最初になるかを知る方法はありません。私の書き込みは条件文にあります。これが私が持っているものです:
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 + "}")
いくつかの変数first_write = True
を使用して、すべての場所でそれを確認してください。次に、に変更しFalse
ます。
または、データをリストに入れて、最後に1回だけ書き込みます。
もちろん、書き込み用にファイルを最初に1回開いて(前のファイルを削除して)、最後に閉じることもできます。
で、あなたは開いているファイルを持って__init__
いてself.the_file = open(self.output_file, 'w')
、あなたはすべてのクラスでそれにアクセスすることができます。ファイルを閉じるプログラムがいつ終了するかだけではありませんself.the_file.close()
。HTMLParserには、データの最後に呼び出される関数があるかもしれません。
HTMLParser.close()を参照してください-ファイルを閉じるのに適した場所のようです。それを上書きし、おそらくclose()
元のクラスから呼び出す必要がありますHTMLParser
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加