Gary Washington
Gary Washington

Reputation: 107

python can not get search and replace to substitute data

I have tried 30-40 combinations of re.sub, sub(), str.replace(),using generators, assigning variables, using the write function, etc. I have been able to get python to write the "data" to a new file but have not been able to get it to write the "new" data to either a new file or using rb+ on the open "tar" file . Please see code below:

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'

This is the current output printed in the Komodo debugger:

found!
old: 69732070726f6772616d2063616e6e6f742062652072756e20696e20444f5320
new: 69732070726f6772616d2063616e2020202062652072756e20696e20444f5320
data: 4d5a90000300000004000000ffff0000b800000000000000400000000000000000000000000000000000000000000000000000000000000000000000400100000e1fba0e00b409cd21b8014ccd21546869732070726f6772616d2063616e6e6f742062652072756e20696e20444f53206d6f64652e0d0d0a2400000000000000b9ee3e99fd8f50cafd8f50cafd8f50ca3e800fcafc8f50caee870fcaf18f50ca

The "old" and "new" are from the hex.patch file and the "data" is the first 160 bytes from the "tar" exe file. The comment #put search and replace code here! is the area where I had tried all the variations.

Upvotes: 0

Views: 98

Answers (1)

user2379410
user2379410

Reputation:

A simple str.replace should just work, but it is unclear where it went wrong on your end... Please try the following, it should work just fine:

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

Upvotes: 1

Related Questions