pythong-code

Modifying Gcode


I am trying to open a .gcode file, read it, and based on what it reads add a specific number to the number attached to any string that contains 'Z'

Below is a sample of gcode:

G1 Z0.3
G1 F6000 E0
G1 F900 X-14.561 Y14.562 E2.27024
G1 X-14.561 Y-14.561 E4.54048
G1 X14.562 Y-14.561 E6.81071
G1 Z0.8
G0 F12000 X-9.687 Y9.688 Z1.05
G1 Z0.3
G1 F6000 E0
G1 F900 X-14.561 Y14.562 E2.27024
G1 X-14.561 Y-14.561 E4.54048 Z1.50

So for example, it needs to read each line and every time it encounters a string that contains 'Z', take the number associated with it and add 1.5 and then replace it with the new value.

So far this is all I have:

part_path = input(' Enter Directory for Part Number: ')  # Asks user to input directory of part number folder
part_path = part_path.replace(('\\'), '/')  # Converts \ to / in path to avoid escape characters
file_name = input('Enter the file name: ')
file_path = part_path + '/' + file_name + '.gcode'

gc = open(file_path)
gc_content = gc.readlines()
for l in gc_content:
    if 'Z' in l:
        print(l)

I just have the print there as a placeholder to see what is going on. I am confused on how I can take only the ZXXX part of each line, split it from the letter (so split 'Z0.3' into ['Z', '0.3']) so I can turn '0.3' into a float, then add a specific number to it, then replace the old ZXXX string with the new value.

Any help would be much appreciative, thanks!


Solution

  • I think this will work:

    from string import *
    part_path = input(' Enter Directory for Part Number: ')  # Asks user to input directory of part number folder
    part_path = part_path.replace(('\\'), '/')  # Converts \ to / in path to avoid escape characters
    file_name = input('Enter the file name: ')
    file_path = part_path + '/' + file_name + '.gcode'
    
    gc = open(file_path)
    gc_content = gc.readlines()
    for l in gc_content:
        if 'Z' in l:
            l.rstrip()
            dex = l.index('Z')
            num = float(l[dex+1:])
            newnum = num + 1.0
            replace(l, str(num), str(newnum))
    

    Now, you can do whatever you want with num, which is a floating point number. This just finds the position of Z, and takes the rest of the line, which is always the floating point number. It also strips any whitespace from the right side (otherwise we may get 0.3 with whitespace instead of "0.3" to convert to a float. Now, we add 1.0 to num, assigning this value to newnum. Using the string.replace() method, we replace num with newnum.