我是一个 Python 菜鸟,正在尝试编写一个脚本来获取两个 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.")
仍然没有运气。