pythonfileg-code

Changing a file in Python


Recently, Iv'e started to programm in Python. I'm interested in translating lines of G-code :

G1 F1200 X253.644 Y174 Z0.2 E3.05044
G1 X252.388 Y174.497 Z0.2 E3.06822
G1 X251.084 Y174.685 Z0.2 E3.08557

to a txt file of the form :

GoTo(X(253.644), Y(174), Z(0.2))
GoTo(X(252.388), Y(174.497), Z(0.2))
GoTo(X(251.084), Y(174.685), Z(0.2))

I'm not interedsted in the E and F parameters of the G-code. Iv'e tried this code:

with open("C:/Users/ZoharMa/Documents/G code/draft_of_g_code.txt" , 'r') as f:
    for line in f:
        line = line.strip()
        if 'G1' in line:
                new_line =  f'GoTo(X({line.split()[1][1:]}), Y({line.split()[2][1:]}), Z({line.split()[3][1:]}))'
                print(new_line)
                with open("copy.txt", "w") as file:
                    file.write(new_line)
             

but the file I created ( "copy") contains only the final line! ( I'm interested in all lines) I'll appreciate any help! Thank you very much!!!


Solution

  • You're overwriting the output file for each line. (Also, file.write() doesn't add a newline, hence the switch to print(..., file=...).)

    You could open both the input and the output file in one with statement, like so:

    with open("C:/Users/ZoharMa/Documents/G code/draft_of_g_code.txt" , 'r') as input_file, open("copy.txt", "w") as output_file:
        for line in input_file:
            line = line.strip()
            if 'G1' in line:
                    new_line =  f'GoTo(X({line.split()[1][1:]}), Y({line.split()[2][1:]}), Z({line.split()[3][1:]}))'
                    print(new_line)
                    print(new_line, file=output_file)
    

    However, it might be safer to just store the new lines in memory and write at the end:

    new_lines = []
    with open("C:/Users/ZoharMa/Documents/G code/draft_of_g_code.txt", "r") as input_file:
        for line in input_file:
            line = line.strip()
            if "G1" in line:
                new_line = f"GoTo(X({line.split()[1][1:]}), Y({line.split()[2][1:]}), Z({line.split()[3][1:]}))"
                print(new_line)
                new_lines.append(new_line)
    
    with open("copy.txt", "w") as output_file:
        for line in new_lines:
            print(line, file=output_file)
    

    That way you don't end up with a half-written file if your program fails.