因此,我写了一个小脚本,将转换我的g代码文件命令替换为“G01”的“G1”这一切都是完美的工作,但这些文件是非常大的,他们可以结束超过10或20k行代码! 我的问题是,所有代码转换后的文件最终有4715行,而原始文件有4817行。有趣的是for循环遍历了所有的行,但只写入了前4715行(我检查了一个简单的a=a+1,每次有东西写入文件)!你知道吗
这里的代码很简单!你知道吗
import string
a = 0
b = 0
s = open("test.gcode","r+")
replaced = open("test_replaced.gcode","a")
for line in s.readlines():
if "G01" in line:
replaced.write(line.replace("G01", "G1" ))
print ("G01 ==> G1")
a = a + 1
elif "G00" in line:
replaced.write(line.replace("G00", "G0" ))
print ("G00 ==> G0")
a = a + 1
else:
replaced.write(line.replace("******", "**" ))
print ("***")
a = a + 1
b = b + 1
#replaced.write(line.replace("G01", "G1" ))
#replaced.write(line.replace("G00", "G0" ))
print ("Done! - " + str(a) + " number of operations done!")
print ("Loopcount: " + str(b))
s.close()
正如在对您的问题的评论中指出的,您可能应该用
with
语句替换您的open()
语句。所以,你的代码会变成。你知道吗请注意,脚本末尾不再有
close()
,因为上下文管理器(with
)已经关闭了文件。你知道吗所有处理文件的代码都需要在
with
块中。你知道吗您可以找到有关上下文管理器here的更多信息。你知道吗
相关问题 更多 >
编程相关推荐