Skip to main content
 首页 » 编程设计

Python:将二进制数据 block 写入和读取文件

2024年10月24日13wuhuacong

我正在编写一个脚本,它将另一个 python 脚本分解成 block 并使用 pycrypto 来加密这些 block (到目前为止我已经成功完成了所有这些),现在我将加密的 block 存储到一个文件中,以便解密器可以读取它并执行每个 block 。加密的最终结果是二进制输出列表(类似于 blocks=[b'\xa1\r\xa594\x92z\xf8\x16\xaa',b'xfbI\xfdqx|\xcd\xdb\x1b\xb3',等等...]).

将输出写入文件时,它们最终都变成了一个大行,因此在读取文件时,所有字节都以一个大行返回,而不是原始列表中的每个项目。我还尝试将字节转换为字符串,并在每个字节的末尾添加一个 '\n' ,但问题是我仍然需要字节,但我无法弄清楚如何撤消字符串以获得原始字节。

总结一下,我希望:将每个二进制项写入文件中的单独一行,以便我可以轻松读取数据并在解密中使用它,或者我可以将数据转换为字符串并在decrpytion 撤消字符串以取回原始二进制数据。

这是写入文件的代码:

    new_file = open('C:/Python34/testfile.txt','wb') 
    for byte_item in byte_list: 
        # This or for the string i just replaced wb with w and 
        # byte_item with ascii(byte_item) + '\n' 
        new_file.write(byte_item) 
    new_file.close() 

读取文件:

    # Or 'r' instead of 'rb' if using string method 
    byte_list = open('C:/Python34/testfile.txt','rb').readlines() 

请您参考如下方法:

文件是没有任何隐含结构的字节流。如果你想加载一个二进制 blob 列表,那么你应该存储一些额外的元数据来恢复结构,例如,你可以 use the netstring format :

#!/usr/bin/env python 
blocks = [b'\xa1\r\xa594\x92z\xf8\x16\xaa', b'xfbI\xfdqx|\xcd\xdb\x1b\xb3'] 
 
# save blocks 
with open('blocks.netstring', 'wb') as output_file: 
    for blob in blocks: 
        # [len]":"[string]"," 
        output_file.write(str(len(blob)).encode()) 
        output_file.write(b":") 
        output_file.write(blob) 
        output_file.write(b",") 

回读它们:

#!/usr/bin/env python3 
import re 
from mmap import ACCESS_READ, mmap 
 
blocks = [] 
match_size = re.compile(br'(\d+):').match 
with open('blocks.netstring', 'rb') as file, \ 
     mmap(file.fileno(), 0, access=ACCESS_READ) as mm: 
    position = 0 
    for m in iter(lambda: match_size(mm, position), None): 
        i, size = m.end(), int(m.group(1)) 
        blocks.append(mm[i:i + size]) 
        position = i + size + 1 # shift to the next netstring 
print(blocks) 

作为替代方案,您可以 consider BSON format for your data或 ascii armor format .