如何从二进制文件中的偏移量写入字节?

How to write bytes from input with offsets in a binary file?

我正在尝试使用下面的脚本创建一个 bin 文件,该文件应从用户输入中写入字节,并在每个字符之间添加偏移字节。但是有一个问题,它按顺序写入所有字节,并且在每个字节之后没有分开,添加了用 'shift'.

定义的偏移字节

offset is 2 bytes    p        y        t        h        o        n
00000000 00000000 00110001 00110001 00110001 00110000 00110000 00110000 00110000 00000000 00000000 00000000

我希望它成为什么样子

offset 2 bytes      p      offset 2 bytes      y      offset 2 bytes        t    offset 2 bytes , etc
00000000 00000000 00110001 00000000 00000000 00110001 00000000 00000000 00110001 00000000 00000000 00110000 00000000 00000000 00110000 00000000 00000000 00110000 00000000 00000000 00110000 00000000 0000000

这是程序的代码

fdata = open("text.bin","wb")
fmeta = open("key.bin","w+b")
print('Enter text:')
txt='python' # input()
l=len(txt)
print(l, 'bytes')
strtobin= ' '.join(format(x, 'b') for x in bytearray(txt, 'utf-8'))
print(strtobin)

# even bytes in key [xor 1]
for v in range(0, 25, 2):
    #print(v)
    fmeta.seek(v)
    fmeta.write(bytes(0))

shift=int(2)
sh=shift.to_bytes(1, byteorder='big')
# odd bytes in key 
for a in range(1,25):
    if a % 2 != 0:
        #print(a)
        fmeta.seek(a)
        fmeta.write(sh)

# text bin [xor 2]
pos=0
#for i in range(1,10): #(len(txt)+10)
for elem in strtobin.split():
    el1=elem.encode('ascii')
    print (el1)
    #print(elem)
    pos = pos + sh
    fdata.seek(pos,1)
    fdata.write(el1)

也许我误解了你的意图,但你的代码看起来非常复杂。

为什么不只是

for ch in text:
     <Not sure if you want to write 2 0's or skip two bytes>
     Write ch as a byte

跳过两个字节是file.seek(2, 1)

你可以这样做:

from pathlib import Path

PAD = b'\x00[=10=]'

with Path("in.txt").open("r") as infile, Path("out.bin").open("wb") as  out_file:
    for line in infile:
        for char in line:
            out_file.write(PAD)
            out_file.write(char.encode())
     out_file.write(PAD)

只需在每个字符后和文件末尾写上 PAD

如果 "in.txt" 只包含字符串 "python",应该或多或少地重现您想要的输出。