gpt4 book ai didi

python-3.x - 在第一次写入时覆盖文本文件,然后附加到它 - Python

转载 作者:行者123 更新时间:2023-12-04 00:49:28 24 4
gpt4 key购买 nike

我第一次写入文件需要覆盖它,然后我的下一个需要附加到它。但是没有办法知道首先写什么。我的写作是在条件语句中。这是我所拥有的:

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 + "}")

最佳答案

添加一个包含更改标志的类属性:

import itertools

class MyHTMLParser(HTMLParser):
def __init__(self, ...):
...
self.modes = itertools.chain('w', itertools.cycle('a'))

@property
def mode(self):
return next(self.modes)

def handle_starttag:
...
with open(filepath, self.mode) as the_file: # self.mode is 'w' the first time and 'a' every time thereafter
# write stuff

关于python-3.x - 在第一次写入时覆盖文本文件,然后附加到它 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24717365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com