我是一个Python noob,我正在尝试编写一个脚本来获取两个Intel hex文件(一个用于我的应用程序代码,一个用于引导程序),从第一个文件中删除EOF记录,附加第二个文件到第一个的剥离版本,并保存为新文件。我已经完成了所有工作,但后来又决定变得更加高兴:我想确保第一个文件的最后一行真正与英特尔EOF记录格式相匹配。但是我似乎无法正确地获取此条件的语法。
appFile = open("MyAppFile.hex", "r")
lines = appFile.readlines()
appFile.close()
appStrip = open("MyAppFile and BootFile.hex",'w')
if appStrip.readline[:] == ":00000001FF": #Python complains about "builtin_function_or_method" not subscriptable here
appStrip.writelines([item for item in lines[:-1]])
appStrip.close()
else:
print("No EOF record in last line. File may be corrupted.")
appFile = open("MyAppFile and BootFile", "r")
appObcode = appFile.read()
appFile.close()
bootFile = open("MyBootFile", "r")
bootObcode = bootFile.read()
bootFile.close()
comboData = appObcode + bootObcode
comboFile = open("MyAppFile and BootFile", "w")
comboFile.write(comboData)
comboFile.close()
对于更清洁或更安全版本的任何其他建议也是受欢迎的。
更新: 添加了一行来打印最后一行;我得到了预期的输出,但每次比较仍然失败。这是当前的完整计划:
appFile = open("C:/LightLock/Master/Project/Debug/Exe/Light Lock.hex")
appLines = appFile.readlines()
appFile = open("MyAppFile.hex").read()
EOF = appLines[len(appLines)-1]
print(appLines[len(appLines)-1])
if not EOF == (":00000001FF"):
print("No EOF record in last line of file. File may be corrupted.")
else:
with open("MyAppFile Plus Boot", "a") as appStrip:
appStrip.writelines([item for item in appLines[:-1]])
with open("MyAppFile Plus Boot.hex", "r") as appFile:
appObcode = appFile.read()
with open("MyBootFile.hex", "r") as bootFile:
bootObcode = bootFile.read()
comboData = appObcode + bootObcode
with open("MyAppFile Plus Boot.hex", "w") as comboFile:
comboFile.write(comboData)
UPDATE2: 尝试修改支票以包括回车和换行,如下所示:
EOF = appLines[len(appLines)-1]
print(EOF)
if EOF != (":00000001FF","\r","\n"):
print("No EOF record in last line of file. File may be corrupted.")
仍然没有运气。
答案 0 :(得分:0)
这是一个更简单的版本:
app = open("app.hex").read()
if not app.endswith(":00000001FF"):
print("No EOF")
combo = open("combo.hex","w")
combo.write(app)
boot = open("boot.hex").read()
combo.write(boot)
combo.close() # it's automatic after program ended
答案 1 :(得分:0)
最后想通了:我写了一些测试代码来输出Python正在读取的字符串的长度。事实证明它只有12个字符,但只显示了11个字符。所以我知道其中一个“看不见的”字符必须是回车或换行。试过两个;原来是换行(新线)。
这是最终的(有效但“未优化”)代码:
appFile = open("MyAppFile.hex")
appLines = appFile.readlines()
appFile = open("MyAppFile.hex").read()
EOF = appLines[len(appLines)-1]
if EOF != (":00000001FF\n"):
print("No EOF record in last line of file. File may be corrupted.")
else:
with open("MyAppFile and Boot.hex", "a") as appStrip:
appStrip.writelines([item for item in appLines[:-1]])
with open("MyAppFile and Boot.hex", "r") as appFile:
appObcode = appFile.read()
with open("MyBootFile.hex", "r") as bootFile:
bootObcode = bootFile.read()
comboData = appObcode + bootObcode
with open("MyAppFile and Boot.hex", "w") as comboFile:
comboFile.write(comboData)