Python:将二进制数据块写入和读取文件
Python: write and read blocks of binary data to a file
我正在编写一个脚本,它将另一个 python 脚本分解成块并使用 pycrypto 加密块(到目前为止我已经成功完成了所有这些),现在我正在存储加密块到一个文件,以便解密器可以读取它并执行每个块。加密的最终结果是二进制输出列表(类似于 blocks=[b'\xa1\r\xa594\x92z\xf8\x16\xaa',b'xfbI\xfdqx|\xcd\xdb\x1b\xb3',etc...]
)。
将输出写入文件时,它们最终都变成了一个大行,因此在读取文件时,所有字节都以一个大行返回,而不是原始列表中的每个项目。我还尝试将字节转换为字符串,并在每个字节的末尾添加一个 '\n'
,但问题是我仍然需要字节,而且我不知道如何撤消字符串到获取原始字节。
总而言之,我希望:将每个二进制项写入文件中的单独一行,以便我可以轻松读取数据并在解密中使用它,或者我可以将数据转换为字符串并在解密中撤消字符串以取回原始二进制数据。
这是写入文件的代码:
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()
我想你要找的是 byte_list=open('C:/Python34/testfile.txt','rb').read()
如果您知道每个项目有多少字节,则可以使用 read(number_of_bytes)
一次处理一个项目。
read()
将读取整个文件,然后由您将整个字节列表解码为各自的项目。
一般来说,由于您使用的是 Python 3,因此您将使用 bytes
objects (which are immutable) and/or bytearray
个对象(可变的)。
示例:
b1 = bytearray('hello', 'utf-8')
print b1
b1 += bytearray(' goodbye', 'utf-8')
print b1
open('temp.bin', 'wb').write(b1)
#------
b2 = open('temp.bin', 'rb').read()
print b2
输出:
bytearray(b'hello')
bytearray(b'hello goodbye')
b'hello goodbye'
文件是没有任何隐含结构的字节流。如果你想加载一个二进制 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 or ascii armor format。
我正在编写一个脚本,它将另一个 python 脚本分解成块并使用 pycrypto 加密块(到目前为止我已经成功完成了所有这些),现在我正在存储加密块到一个文件,以便解密器可以读取它并执行每个块。加密的最终结果是二进制输出列表(类似于 blocks=[b'\xa1\r\xa594\x92z\xf8\x16\xaa',b'xfbI\xfdqx|\xcd\xdb\x1b\xb3',etc...]
)。
将输出写入文件时,它们最终都变成了一个大行,因此在读取文件时,所有字节都以一个大行返回,而不是原始列表中的每个项目。我还尝试将字节转换为字符串,并在每个字节的末尾添加一个 '\n'
,但问题是我仍然需要字节,而且我不知道如何撤消字符串到获取原始字节。
总而言之,我希望:将每个二进制项写入文件中的单独一行,以便我可以轻松读取数据并在解密中使用它,或者我可以将数据转换为字符串并在解密中撤消字符串以取回原始二进制数据。
这是写入文件的代码:
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()
我想你要找的是 byte_list=open('C:/Python34/testfile.txt','rb').read()
如果您知道每个项目有多少字节,则可以使用 read(number_of_bytes)
一次处理一个项目。
read()
将读取整个文件,然后由您将整个字节列表解码为各自的项目。
一般来说,由于您使用的是 Python 3,因此您将使用 bytes
objects (which are immutable) and/or bytearray
个对象(可变的)。
示例:
b1 = bytearray('hello', 'utf-8')
print b1
b1 += bytearray(' goodbye', 'utf-8')
print b1
open('temp.bin', 'wb').write(b1)
#------
b2 = open('temp.bin', 'rb').read()
print b2
输出:
bytearray(b'hello')
bytearray(b'hello goodbye')
b'hello goodbye'
文件是没有任何隐含结构的字节流。如果你想加载一个二进制 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 or ascii armor format。