Python 写入文件相同的字节数
Python writing to file same amount of bytes
我正在尝试编写 Pcap 生成器,我想将固定长度的字节写入文件。我嗅探的帧长度显然总是可变的,但我也应该在 Pcap 数据包头中定义这个长度。我设置为1500字节。有没有什么办法可以将前导零添加到字节对象中,使其达到 1500 字节?
使用bytes.zfill
.
>>> bs = bytes([1, 2, 3])
>>> bs
b'\x01\x02\x03'
>>> padded = bs.zfill(10)
>>> padded
b'0000000\x01\x02\x03'
这是 bytes.zfill
的 documentation:
bytes.zfill(width)
bytearray.zfill(width)
Return a copy of the sequence left filled with ASCII b'0'
digits to make a sequence of length width
. A leading sign prefix (b'+'
/ b'-'
is handled by inserting the padding after the sign character rather
than before. For bytes
objects, the original sequence is returned if
width is less than or equal to len(seq)
.
我正在尝试编写 Pcap 生成器,我想将固定长度的字节写入文件。我嗅探的帧长度显然总是可变的,但我也应该在 Pcap 数据包头中定义这个长度。我设置为1500字节。有没有什么办法可以将前导零添加到字节对象中,使其达到 1500 字节?
使用bytes.zfill
.
>>> bs = bytes([1, 2, 3])
>>> bs
b'\x01\x02\x03'
>>> padded = bs.zfill(10)
>>> padded
b'0000000\x01\x02\x03'
这是 bytes.zfill
的 documentation:
bytes.zfill(width)
bytearray.zfill(width)
Return a copy of the sequence left filled with ASCII
b'0'
digits to make a sequence of lengthwidth
. A leading sign prefix (b'+'
/b'-'
is handled by inserting the padding after the sign character rather than before. Forbytes
objects, the original sequence is returned if width is less than or equal tolen(seq)
.