在文件中找不到大于32KB的块

2024-03-29 12:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

检查大量文件中是否有零块的最快方法是什么。块应大于32000字节的零。 以下代码将减慢速度:

empty_blocks = []
min_length = 32000
block = False
begin = -1
data = open(file_name,'rb').read()
for i,byte in enumerate(data):
        byte = ord(byte)
        if byte == 0x00 and block == False:
            block = True
            begin = i
        elif byte != 0x00 and block == True:
            block = False
            if length >= min_length:
                empty_blocks.append((begin, i - begin))
            begin = -1

Tags: and方法falsetruedataifbytemin
2条回答

因此,假设块大小为32768字节,我得出如下结论:

from functools import partial

BLOCKSIZE = 32 * 1024

with open('testfile.bin', 'rb') as f:
    for block_number, data in enumerate(iter(partial(f.read, BLOCKSIZE), b'')):
        if not any(data):
            print('Block #{0} is empty!'.format(block_number))

sum()是确定序列中每个字节是否都有零值的最快方法。我认为它不可能比O(n)更快。
VPfB建议使用any(),这非常快,因为它终止于第一个非零元素,而不是遍历整个序列。你知道吗

输出示例:

Block #0 is empty!
Block #100 is empty!
Block #200 is empty!

我希望在我的机器上处理速度足够快。你知道吗

从映射文件开始:

import mmap, os, re
f = open(filename)
m = mmap.mmap(f.fileno(), os.fstat(f.fileno()).st_size, prot=mmap.PROT_READ)

使用正则表达式很方便:

for match in re.findall(b'\0{32768}, m):
    print(match.start())

但弦的速度更快:

z32k = '\0' * 32768
start = 0
while True:
    start = m.find(z32k, start)
    if start < 0:
        break
    print(start)

仅32k对齐块:

for match in re.finditer('.{32768}', m, re.DOTALL):
    if max(match.group()) == '\0':
        print(match.start())

相关问题 更多 >