I’m just re(learning) python after 5+ years of inactivity; it doesn’t help that I wasn’t great at it to begin with though… Here is what I’m trying to do:
Individually both sets of code work as expected. I’ve tried lots of different ways to add both sets of code together, but nothing works.
Sample file (C:\gcode\aaaa.gcode)
# start of file
some text
other text
# more text
G00 X1 Y1
G00 X2 Y2
# other text
G00 X3 Y3
G00 X4 Y4
#end of file
For the end result, I would like to have:
# start of file
some text
other text
# more text
G1 X1 Y1 Z0.3
G1 X2 Y2 Z0.3
# other text
G1 X3 Y3 Z0.3
G1 X4 Y4 Z0.3
#end of file
Sample code / result
Code:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
else:
fout.write(line)
Result:
# start of file
some text
other text
# more text
G1 X1 Y1
G1 X2 Y2
# other text
G1 X3 Y3
G1 X4 Y4
#end of file
Code:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
else:
fout.write(line)
Result
# start of file
some text
other text
# more text
G00 X1 Y1 Z0.3
G00 X2 Y2 Z0.3
# other text
G00 X3 Y3 Z0.3
G00 X4 Y4 Z0.3
#end of file
I've tried various offshoots of the code below, but I always get the following error message:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
fout = fout.replace('G00', 'G1') # newly added line
else:
fout.write(line)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'
You are attempting doing .replace
on file handle - this does not make sense, you should do it on line
for example:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
line = line.replace('G00', 'G1')
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
else:
fout.write(line)
Note also that your code would work correctly if and only if lines are \r
-delimited.
Thanks! I was able to get it to work. The only thing I had to change was if line.startswith('G00'): to if line.startswith('G1'):