Warm tip: This article is reproduced from serverfault.com, please click

Find, Replace, and Concatenate strings

发布于 2020-12-02 15:36:18

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:

  1. find a sting in a file and replace it with another string (G00 with G1)
  2. find all of the instances where a line starts with a specific string and concatenate a string on it at the end
  3. The original file aaaa.gcode remains untouched and all of the changes are saved to bbbb.gcode.

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

  1. find replace - G00 with G1
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
  1. Concatenate a string - add Z0.3 if line starts with G00
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'
Questioner
Muldoon
Viewed
0
Daweo 2020-12-02 23:53:19

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.