更改 Python 中的文件

Changing a file in Python

最近,我开始在 Python 中编程。 我对翻译 G 代码行很感兴趣:

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

到格式为 :

的 txt 文件
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))

我对 G 代码的 E 和 F 参数不感兴趣。 我试过这段代码:

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)
             

但我创建的文件(“复制”)只包含最后一行! (我对所有线路都感兴趣) 我会很感激任何帮助!非常感谢!!!

您正在覆盖每一行的输出文件。 (此外,file.write() 不添加换行符,因此切换到 print(..., file=...)。)

您可以在一个 with 语句中同时打开输入和输出文件,如下所示:

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)

但是,将新行存储在内存中并在末尾写入可能更安全:

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)

这样,如果您的程序失败,您就不会得到一个写到一半的文件。