Python的读写文件是将最终输出文件剪切到有限的行数吗?

2024-09-28 16:57:47 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我写了一个小脚本,将转换我的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()

Tags: 文件代码intestforlineopenreplace
1条回答
网友
1楼 · 发布于 2024-09-28 16:57:47

正如在对您的问题的评论中指出的,您可能应该用with语句替换您的open()语句。所以,你的代码会变成。你知道吗

...
with open("test.gcode","r+") as s:
    with open("test_replaced.gcode","a") as replaced:
        ...
print ("Done! - " + str(a) + " number of operations done!")
print ("Loopcount: " + str(b))

请注意,脚本末尾不再有close(),因为上下文管理器(with)已经关闭了文件。你知道吗

所有处理文件的代码都需要在with块中。你知道吗

您可以找到有关上下文管理器here的更多信息。你知道吗

相关问题 更多 >