【发布时间】:2014-09-03 05:42:49
【问题描述】:
我对文件的第一次写入需要覆盖它,然后我的下一个需要附加到它。但是没有办法知道先写什么。我的写作是在条件语句中。这是我所拥有的:
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 -
或者把数据放在某个列表上,最后只写一次。
-
当然你可以在开头打开文件写入一次(删除之前的文件),最后关闭。
-
@furas 谢谢,你的列表想法会奏效。您将如何打开一次然后在最后关闭?干杯。
-
in
__init__做self.the_file = open(self.output_file, 'w')并且您有打开的文件,您可以在所有课程中访问它。我不只知道程序何时结束以关闭文件self.the_file.close()。也许HTMLParser在数据末尾调用了一些函数。
标签: python-3.x output