Search .gcode file for string starting with specific letters

127 Views Asked by At

I have a file called test.gcode. This file contains the following data:

N100(ROUGH FACE/OD - CNGP-432HP KC5410 ) 
G00G20G40G54G99X10.0Z10.0T0000 
G00T0101 
G50S2200 
G97S1400M03P11 
G96S1200 
G00X3.8(X3.7)Z.2M8 
Z.03 
G1Z.005F.020 
X-.07F.01
G00Z.1 
G00X3.523
Z.03 
G1Z-2.F.015
X3.8(X3.763) 
G00Z.2 
M9 
G00G40X10.0Z10.0T0000
M01
 
N200(CUTOFF - .118 WIDE TAG N3A IC20 ) 
G00G20G40G54G99X10.0Z10.0T0000 
G00T0303 
G97S429M03 
G96S400
G00X3.563Z.2M8 
Z-.173 
G1X3.335F.0025 
G00X3.563
Z-.211 
G1X3.335 
G00X3.563
G50S1800 

You will notice each 'block' of code is separated by a line break and identified by a 'N Code' (my description) in the first line of each 'block'. So for this example, we have two 'blocks': N100 and N200.

Within each 'code block' there is a string that contains 'T', a 'T Code', (my description) that is NOT EQUAL to T0000.

In this example the 'T Code' for the N100 block is 'T0101' and the 'T Code' for the N200 block is 'T0303'

I would like to read this file and output a txt file that contains the following:

N100:T0101
N200:T0303

So far I have the following:

import re
pattern = re.compile("^N")

for line in open("test.gcode"):
    for match in re.finditer(pattern, line):
        print(line)

I am stumped on how to find the associated T value for each block and write out to file.

Any help would be greatly appreciated!

1

There are 1 best solutions below

0
On

You can do this without re by splitting the data on the newlines. Note that this answer assumes that each line has a trailing space, like your sample.

with open("test.gcode", "r") as data:
    items = [i.split("\n")for i in data.split("\n \n")]
    itemlist = [i[0].split("(")[0] + ':' + i[2][3:].strip() for i in items]
    with open("outfile.txt", "w") as outfile:
        outfile.write("\n".join(itemlist))