Search code examples
pythoniopcappacket-sniffers

Python writing to file same amount of bytes


I was trying to write Pcap generator and I want to write fixed length of bytes to file. Frame length that I sniff is always changeable obviously but I should also define this length in Pcap packet header. I set it as 1500 bytes. Is there any way to put leading zeros to byte object that complete it to 1500 bytes?


Solution

  • Use bytes.zfill.

    >>> bs = bytes([1, 2, 3])
    >>> bs
    b'\x01\x02\x03'
    >>> padded = bs.zfill(10)
    >>> padded
    b'0000000\x01\x02\x03'
    

    This is the documentation for bytes.zfill:

    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).