我已经尝试了30-40种re.sub,sub(),str.replace(),使用生成器,分配变量,使用write函数等组合。我已经能够得到python来编写&# 34;数据"到一个新文件,但无法让它写出" new"数据到新文件或在开放的" tar"上使用rb +档案。请参阅以下代码:
modcwd = os.getcwd() #assign var to modman DIR
patch = 'hex.patch' #hardcode patch to var
tar = 'Hex!.exe' #hardcode patch to var
alphex = 'h' #hardcode patch to var
patlst = [line.strip() for line in open(patch,'rb',1)] #Read Patch start
if alphex == 'h' :
old = patlst[patlst.index('OLD:')+1] #get old data str
new = patlst[patlst.index('NEW:')+1] #get new data str
old = old.lower();old = ''.join(old.split())
new = new.lower();new = ''.join(new.split())
pircwd = os.chdir('..'); pircwd = os.getcwd() ##DIR change
with open(tar,'rb') as f:
data = binascii.hexlify(f.read(160))
if old in data:
print 'found!'
print 'old:',old;print 'new:',new;print'data:',data
#put search and replace code here!
else:
print 'not found'
这是Komodo调试器中打印的当前输出:
found!
old: 69732070726f6772616d2063616e6e6f742062652072756e20696e20444f5320
new: 69732070726f6772616d2063616e2020202062652072756e20696e20444f5320
data: 4d5a90000300000004000000ffff0000b800000000000000400000000000000000000000000000000000000000000000000000000000000000000000400100000e1fba0e00b409cd21b8014ccd21546869732070726f6772616d2063616e6e6f742062652072756e20696e20444f53206d6f64652e0d0d0a2400000000000000b9ee3e99fd8f50cafd8f50cafd8f50ca3e800fcafc8f50caee870fcaf18f50ca
" old"和"新"来自hex.patch文件和"数据"是" tar"的前160个字节。 exe文件。注释#put搜索并替换代码!是我尝试过所有变化的区域。
答案 0 :(得分:1)
一个简单的str.replace
应该可行,但目前还不清楚你到底出错的地方......请尝试以下方法,它应该可以正常工作:
if old in data:
print 'found!'
print 'old:',old
print 'new:',new
print 'data:',data
#put search and replace code here!
data = data.replace(old, new)
print 'new data:', data