【发布时间】:2015-02-26 11:55:41
【问题描述】:
我正在尝试读取二进制文件并匹配其每条记录中的数字。 如果数字匹配,则将记录复制到另一个文件。 该数字应出现在每条记录的第 24 到第 36 个字节之间。
脚本将数字作为参数。这是我正在使用的脚本:
#!/usr/bin/env python
# search.py
import re
import glob
import os
import binascii
list = sys.argv[1:]
list.sort()
rec_len=452
filelist = glob.glob(os.getcwd() + '*.bin')
print('Input File : %s' % filelist)
for file in filelist:
outfile = file + '.out'
f = open(file, "rb")
g = open(outfile, "wb")
for pattern in list:
print pattern
regex_search = re.compile(pattern).search
while True:
buf = f.read(rec_len)
if len(buf) == 0:
break
else:
match = regex_search(buf)
match2=buf.find(pattern)
#print match
#print match2
if ((match2 != -1) | (match != None )):
g.write(buf)
f.close()
g.close()
print ("Done")
我正在运行它:
python search.py 1234 56789
我正在使用 python 2.6。 代码与号码不匹配。 我还尝试在匹配之前使用 binascii 将数字转换为二进制,但即便如此它也没有返回任何记录。
如果我给任何字符串它可以正常工作,但如果我给任何数字作为参数它不匹配。
我哪里出错了?
【问题讨论】:
标签: binary pattern-matching python-2.6