我是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)python脚本遍历该文件以查找行“ 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)
这是较大函数的一部分,并且“ APPL_End_address
”作为参数提供
5)当我运行此代码,并且新的十六进制地址为5个十六进制数字宽时,我得到以下输出:
似乎新的十六进制地址已正确写入,但下一行的第一个字符已删除。有什么想法吗?
尝试一下,简单得多。
with open("Fileout.txt",'w') as f:
for line in inputFile:
if "LVMain_StartAddress=" in line:
line = line.replace(line.split("=")[1],APPL_End_address)
f.write("%s\n" % line)
else:
f.write("%s" % line)