Dec-07-2019, 08:12 AM
(This post was last modified: Dec-07-2019, 08:13 AM by Gribouillis.)
You need to parse the input one way or another. Here is a simple parser. It reads the input lines and for each line it calls a method
Here is the (untested) code
line_event()
. Initially this method simply outputs the line to the output file. If it meets a line starting with .CURVE
, it changes the method to line_event_curve_header()
which outputs the lines until it meets a line ..NE
. In the meanwhile it detects if it meets a line starting with ...A_Z or ...B_Z
. After the last line of the header, if ...A_Z or ...B_Z has not been found it changes the method to line_event_curve_body()
which appends 0.00 to the lines until it meets a line starting a new object.Here is the (untested) code
import re class Parser: object_pattern = re.compile(r'^[.](CURVE|POINT|TEXT)') def __init__(self, infile, outfile): self.infile = infile self.outfile = outfile self.line_event = self.line_event_base def run(self): for line in self.infile: self.line_event(line) self.outfile.flush() def line_event_base(self, line): if line.startswith('.CURVE'): self.start_curve(line) else: self.outfile.write(line) def line_event_curve_header(self, line): if line.startswith('...A_Z') or line.startswith('...B_Z'): self.seen_ab_z = True self.output.write(line) elif line.rstrip('\n') == '..NE': if self.seen_ab_z: self.line_event = self.line_event_base self.output.write(line) else: self.output.write('...A_Z 0.00\n...B_Z 0.00\n..NEZ\n') self.line_event = self.line_event_curve_body else: self.output.write(line) def line_event_curve_body(self, line): if self.object_pattern.match(line): if line.startswith('.CURVE'): self.start_curve(line) else: self.line_event = self.line_event_base self.outfile.write(line) else: self.outfile.write(line.rstrip('\n')) self.outfile.write(' 0.00\n') def start_curve(self, line): self.line_event = self.line_event_curve_header self.seen_ab_z = False self.line_event(line) if __name__ == '__main__': with open('C:/Users/sufi/Desktop/info.txt','r') as infile,\ open('C:/Users/sufi/Desktop/info_edit.txt','w') as outfile: Parser(infile, outfile).run()