How to modify a text file?

前端 未结 8 1569
不思量自难忘°
不思量自难忘° 2020-11-22 03:14

I\'m using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

8条回答
  •  梦谈多话
    2020-11-22 03:49

    Wrote a small class for doing this cleanly.

    import tempfile
    
    class FileModifierError(Exception):
        pass
    
    class FileModifier(object):
    
        def __init__(self, fname):
            self.__write_dict = {}
            self.__filename = fname
            self.__tempfile = tempfile.TemporaryFile()
            with open(fname, 'rb') as fp:
                for line in fp:
                    self.__tempfile.write(line)
            self.__tempfile.seek(0)
    
        def write(self, s, line_number = 'END'):
            if line_number != 'END' and not isinstance(line_number, (int, float)):
                raise FileModifierError("Line number %s is not a valid number" % line_number)
            try:
                self.__write_dict[line_number].append(s)
            except KeyError:
                self.__write_dict[line_number] = [s]
    
        def writeline(self, s, line_number = 'END'):
            self.write('%s\n' % s, line_number)
    
        def writelines(self, s, line_number = 'END'):
            for ln in s:
                self.writeline(s, line_number)
    
        def __popline(self, index, fp):
            try:
                ilines = self.__write_dict.pop(index)
                for line in ilines:
                    fp.write(line)
            except KeyError:
                pass
    
        def close(self):
            self.__exit__(None, None, None)
    
        def __enter__(self):
            return self
    
        def __exit__(self, type, value, traceback):
            with open(self.__filename,'w') as fp:
                for index, line in enumerate(self.__tempfile.readlines()):
                    self.__popline(index, fp)
                    fp.write(line)
                for index in sorted(self.__write_dict):
                    for line in self.__write_dict[index]:
                        fp.write(line)
            self.__tempfile.close()
    

    Then you can use it this way:

    with FileModifier(filename) as fp:
        fp.writeline("String 1", 0)
        fp.writeline("String 2", 20)
        fp.writeline("String 3")  # To write at the end of the file
    

提交回复
热议问题