【问题标题】:ASCII number pattern matching in binary file in Python 2Python 2中二进制文件中的ASCII数字模式匹配
【发布时间】: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


    【解决方案1】:

    通过读取检查第一个模式的所有字节,您正在耗尽文件缓冲区。因此,第二个模式永远不会匹配(甚至不会进行尝试),因为您已经通过在第一个模式的 for 循环运行期间读取所有记录来到达文件的末尾。

    这意味着如果在这些记录中找不到您的第一个模式,您的脚本将不会给您任何输出。

    考虑在 while 循环的末尾添加 f.seek(0),或者更改两个循环结构的顺序,以便您首先从文件中读取一条记录,然后 匹配参数列表中每个模式的正则表达式。

    另外,尽量不要使用list 作为数组名称来隐藏python 内置函数。它不会在您显示的代码中给您带来问题,但您绝对应该注意这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      相关资源
      最近更新 更多