用python对大文件执行xoring

2024-10-03 23:18:15 发布

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

我试图对一些文件应用xOr操作,其中一些文件非常大。
基本上我得到了一个文件,并逐字节对其进行异或(或者至少我认为我正在这样做)。当它碰到一个更大的文件(大约70MB)时,我得到一个内存不足的错误,我的脚本崩溃。
我的电脑有16GB的Ram,其中50%以上可用,因此我不会将其与硬件联系起来。在

def xor3(source_file, target_file):
    b = bytearray(open(source_file, 'rb').read())
    for i in range(len(b)):
        b[i] ^= 0x71
    open(target_file, 'wb').write(b)

我试图分块读取文件,但似乎我太没经验了,因为输出不是所需的。当然,第一个函数返回我想要的:)

^{pr2}$


这种手术的合适解决方案是什么?我做错什么了?在


Tags: 文件脚本sourcetarget硬件def错误open
3条回答

除非我弄错了,否则在第二个示例中,您通过调用bytearray并将其分配给b来创建{}的副本。然后修改b,但返回{}。 b中的修改对data本身没有影响。在

懒洋洋地迭代大文件。在

from operator import xor
from functools import partial
def chunked(file, chunk_size):
    return iter(lambda: file.read(chunk_size), b'')
myoperation = partial(xor, 0x71)

with open(source_file, 'rb') as source, open(target_file, 'ab') as target:
    processed = (map(myoperation, bytearray(data)) for data in chunked(source, 65536))
    for data in processed:
        target.write(bytearray(data))

使用seek函数将文件分块获取,并在每次将其附加到输出文件中

CHUNK_SIZE = 1000 #for example

with open(source_file, 'rb') as source:
    with open(target_file, 'a') as target:
        bytes = bytearray(source.read(CHUNK_SIZE))
        source.seek(CHUNK_SIZE)

        for i in range(len(bytes)):
            bytes[i] ^= 0x71

        target.write(bytes)

相关问题 更多 >