我正在處理某個項目。我有C++和Java背景,但我沒有python背景。 我已經給txt文件,如下圖所示:我不能在內部如果else語句達到變量
G1 X000 Y00
X00
Z000
G0 X121.212 Z5.32
X0.00 Y3.000
我需要分別添加G ..到下一行,直到它看到全新G ..。它可以是G1或G0或G5等。所以結果將如下
G1 X000 Y00
G1 X00
G1 Z000
G0 X121.212 Z5.32
G0 X0.00 Y3.000
我的代碼如下。
command = ""
with open('Model.ngc', 'r') as f:
with open("out.txt", "w") as f1:
for line in f:
if line in ['\n', '\r\n']:
f1.write(line)
elif line.startswith('M', 0, 1):
f1.write(line)
else:
command = line.split(' ', 1)[0]
if command == 'G0' or command == 'G00':
command = 'G00'
elif command == 'G1' or command == 'G01':
command = 'G01'
elif command == 'G2' or command == 'G02':
command = 'G02'
elif command == 'G3' or command == 'G03':
command = 'G03'
if (line.startswith('G0 ', 0, 3) or line.startswith('G1 ', 0, 3) or line.startswith('G2 ', 0, 3) or
line.startswith('G3 ', 0, 3) or line.startswith('G4 ', 0, 3) or line.startswith('G5 ', 0, 3) or
line.startswith('G6 ', 0, 3) or line.startswith('G7 ', 0, 3) or line.startswith('G8 ', 0, 3) or
line.startswith('G9 ', 0, 3)):
if command == 'G00':
f1.write(line.replace('G0', 'G00'))
elif command == 'G01':
f1.write(line.replace('G1', 'G01'))
elif command == 'G02':
f1.write(line.replace('G2', 'G02'))
elif command == 'G03':
f1.write(line.replace('G3', 'G03'))
elif command == 'G04':
f1.write(line.replace('G4', 'G04'))
elif command == 'G05':
f1.write(line.replace('G5', 'G05'))
elif command == 'G06':
f1.write(line.replace('G6', 'G06'))
print(command)
else:
# print(line)
if (line.startswith('G00') or line.startswith('G01') or line.startswith('G02') or
line.startswith('G03') or line.startswith('G04') or line.startswith('G05') or
line.startswith('G06') or line.startswith('G07') or line.startswith('G08') or line.startswith('G09')):
# Because it can be already converted
f1.write(line)
else:
f1.write(command + line)
我試圖從上一行得到G1或G0,並分配給命令。有用。當我嘗試在最後其他語句中顯示我的命令 變量爲空時,我不知道如何處理它。
它不工作。 回溯(最近最後調用): 文件 「NgcToGcode.py」,第6行,在 如果字[0]和字[0] [0] == 「G」: IndexError:列表索引超出範圍 –
Soulmaster
你能否檢查一行讀取是否正確?因爲我在控制檯嘗試,只有在這裏共享答案!這段代碼應該在'open(「out.txt」,「w」)後面出現,就像f1:' –
或者讀取行是空的時候!我已經添加了該編輯。 –