1

I have a bunch of hex files that I need to read in to python. I want to break up the contents of the hex file into 4 byte chunks that will then get assigned to columns in a pandas dataframe.

My problem is that the files that I have are currently off-nominal sizes - they need to be multiples of 32 bytes - so I need to zero pad the end of each file so that it's overall size is a multiple of 32. I currently have the below code to read the contents of a hex file into a variable, but I haven't been able to find any information on how to append the right number of bytes (0s) to the end of the file.

gnss_input = "Inputs/TestCommands/Set10Sec" #this is a 67 byte file, needs to be 96 bytes
size = os.path.getsize(gnss_input)
with open(gnss_input,'rb') as file:
  byts = file.read()
  a = binascii.hexlify(byts)

I know how much additional data I need to append by subtracting the current file size from the nearest multiple of 32, but I don't know how to create a string of 0s that equals this size (in bytes) to append to the hex data file.

This is my first time manipulating hex files and any help would be much appreciated!

3
  • You know the current size of the data, you know what size you want, so just calculate the difference wanted - actual and use it to append a bunch of zero bytes to the data. What's the problem here?
    – ForceBru
    Aug 20, 2018 at 22:00
  • @ForceBru how do you append a bunch of zero bytes to the end of the data? I know how to append to a file but how do you append a specific size string of 0s - ie how do I create a string of a specific byte length?
    – kdubs
    Aug 20, 2018 at 22:04
  • Why create a string if you can create an array of bytes directly - a bytearray?
    – ForceBru
    Aug 21, 2018 at 17:45

1 Answer 1

1

This code below will append the appropriate hex values for the file path in gnss_input:

gnss_input = "/home/eric/src/test_pad.txt" #this is a 67 byte file, needs to be 96 bytes
size = os.path.getsize(gnss_input)
if size % 32 != 0:
    pad_number = 32 - (size % 32)
else:
    pad_number = 0
with open(gnss_input,'r+b') as file:
    contents = file.read()  # Read to end of file
    # Do your processing with contents here
    padding = [0x0 for _ in range(pad_number)]  # Create bytearray
    file.write(bytearray(padding))  # Append bytes to the end
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.