【问题标题】:Overwrite text file on first write, then append to it - Python在第一次写入时覆盖文本文件,然后附加到它 - Python
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 非常有趣的解决方案,谢谢。我设法通过在 __init__() 中打开文件并在脚本末尾关闭文件来做到这一点。
【解决方案2】:

使用一些变量first_write = True 并在所有地方检查它。然后改成False

或者将数据放在某个列表中,最后只写一次。

当然你可以在开头打开文件写入一次(删除之前的文件)并在最后关闭它。

__init__self.the_file = open(self.output_file, 'w') 并且你有打开的文件,你可以在所有班级访问它。我不只知道程序何时结束以关闭文件self.the_file.close()。也许 HTMLParser 在数据末尾调用了一些函数。

HTMLParser.close() - 这似乎是关闭文件的好地方。您将不得不覆盖它并可能从原始类HTMLParser 调用close()

【讨论】:

  • 谢谢。我选择在__init__ 中打开文件。我给 htmlparser 这个新函数def close_my_file(self): self.the_file.close() 并在我的脚本末尾调用它。干杯
  • 这很简单,但它增加了很多分支。此外,代码变得不可维护(考虑在 20 个不同的地方编写并在每个地方添加检查)
  • @inspectorG4dget 谢谢。我应该添加支票吗?我没有。每次我写信给文件时,我只写了self.the_file.writelines(self.indent * self.getpos()[1] + '#' + attr[id+1] + ' {' +'\n')
  • 如果你使用first_write = True 方法,那么你应该在每次你想写东西的时候添加检查(不可维护的设计)。如果您将所有内容累积到一个列表中并最终将其写出,那么这会花费大量内存。您可以在__init__ 中打开文件一次并使用文件处理程序在任何地方写入,但这不会像with open(...) as ...: 那样优雅地处理故障。将文件打开模式的顺序保存在实例变量中可以解决所有这些问题,但会占用内存;但是使用一点itertools 魔法,可以减少内存占用。
猜你喜欢
  • 2016-06-11
  • 2011-05-08
  • 2016-04-04
  • 2013-12-26
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2015-04-29
相关资源
最近更新 更多