Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python无法获取搜索和替换来替换数据_Python_Regex_Replace - Fatal编程技术网

python无法获取搜索和替换来替换数据

python无法获取搜索和替换来替换数据,python,regex,replace,Python,Regex,Replace,我尝试了30-40种re.sub、sub()、str.replace()的组合,使用生成器、分配变量、使用write函数等。我能够让python将“数据”写入新文件,但无法让它将“新”数据写入新文件或在打开的“tar”文件上使用rb+。请参阅下面的代码: modcwd = os.getcwd() #assign var to modman DIR patch = 'hex.patch' #hardcode patch to var tar = 'Hex!.exe' #hardcode patch

我尝试了30-40种re.sub、sub()、str.replace()的组合,使用生成器、分配变量、使用write函数等。我能够让python将“数据”写入新文件,但无法让它将“新”数据写入新文件或在打开的“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

“旧”和“新”来自hex.patch文件,“数据”是“tar”exe文件的前160个字节。注释#将搜索和替换代码放在这里!是我尝试过所有变体的地方。

一个简单的
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

我不喜欢你的分号。显示你实际上在尝试什么。你不能写入tar文件,因为当你进入if语句时,它已经被上下文管理器关闭了。缩进这一点,你就可以开始了。@Decenty,Thank没有发现缩进(或缺少)正在结束它。成功了。