我是python的新手,在处理.bat文件时卡住了
1)我有一个.bat文件,其中包含以下几行:
set local_dir=%~d0%~p0
set LVMain_StartAddress=0xfaff
set LVMain_EndAddress=0x0f4ff
set HVMain_StartAddress=0x01d00
set HVMain_EndAddress=0x095ff
set LVMain_StartAddressMerged=0x0D000
set LVMain_EndAddressMerged=0x0fcff
set HVMain_StartAddressMerged=0x01001d00
set HVMain_EndAddressMerged=0x010095dd
2) A python script runs through the file to look for the line "set LVMain_StartAddress=0xfaff
"
3)当找到行时,我想用一个新的十六进制地址代替。有时新的十六进制地址为5个字符长
4)以下是我为此编写的python代码:
# write LVMain start address in .bat file
with open("..\..\..\Tools\Scripts\GenerateRomTestChecksums.bat", "r+") as f:
#read lines individually until we find where to write LvMain Start address
BatFileLine = f.readline()
while( (LVMain_StartPattern in BatFileLine ) == False ):
BatFileLine = f.readline()
#set marker back to the beginning of the line
LineMarker = int(f.tell()) - (int(len(BatFileLine)) + 0x01)
f.seek(LineMarker)
#split string where address starts to write new address in file
name, hex_address = BatFileLine.split('0x')
#append new address and carriage return
name = name + APPL_End_address + "\n"
print(len(name))
contents = f.read(len(BatFileLine)).replace(BatFileLine,name)
f.seek(LineMarker)
f.write(name)
This is part of a larger function and "APPL_End_address
" is given as a parameter
5) When I run this code, and the new hex address is 5 hex digits wide, I get the following output: enter image description here
看来新的十六进制地址已正确写入,但下一行的第一个字符已删除。有什么想法吗?
这是我第一次在这里发布,因此,如果我的解释不清楚,请告诉我:)。另外,请原谅变量名称选择不当。一些评论可能也已过时:)