Skip to content Skip to sidebar Skip to footer

"value Error: Mixing Iteration And Read Methods Would Lose Data "message While Extracting Numbers From A String From A .txt File Using Python

I have a program that grabs numbers from a .txt file and puts it into an array. The problem is that the numbers are not isolated or ordered. The .txt file looks like this: G40 Z=10

Solution 1:

If I understand correctly, you want to combine the Z value from the lines that start with G with the X and Y values from the following lines (until the next G line).

If so, I'd use a single loop, printing only on the lines that start with A and just saving the new Z value on the lines that start with G. I'd do the line parsing with regex, but you could use simple string manipulation if you wanted to (I'd split and then skip the first letter or letters of the relevant items).

import itertools
import re

z = Nonewithopen('circletest1.gcode') as input_file:
    for line in itertools.islice(203, None):  # islice to skip the first 203 linesif line.startswith("G"):
            z = re.search(r"Z=(\d+)", line).group(1)
        elif line.startswith("A"):
            x, y = re.search(r"X(\d+) Y(\d+)", line).groups()
            print(x, y, z)

Post a Comment for ""value Error: Mixing Iteration And Read Methods Would Lose Data "message While Extracting Numbers From A String From A .txt File Using Python"