Read file byte by byte works but get an error at the end

I have a file “0x66,0xff,” etc, ned a buffer (array) with only “66ff” etc.
following script works so long, from the 955 byte file all the 190 values I expect, but throughs me error at the end

Value: ff index: 939
Value: ff index: 944
Value: 55 index: 949
Value: aa index: 954
Traceback (most recent call last):
  File "/Users/mk/PycharmProjects/pythonCAN_Config_1/test.py", line 49, in <module>
    new_value =  get_value(file_contents)			# get native data
  File "/Users/mk/PycharmProjects/pythonCAN_Config_1/test.py", line 33, in get_value
    value = buffer[index]
IndexError: string index out of range

Process finished with exit code 1

and the code


global index
index = 0
correct_file_size = 955

# file content to buffer
def read_file_into_buffer(file_path):
	with open(file_path, 'r') as file:
		file_contents = file.read()
		file.close()
	return file_contents

# clear overhead "0x" and "."
def get_value(buffer):
	global index
	if buffer[index] == ",":
		index += 1				# ignore","
	index+= 2
	value = buffer[index]
	index += 1
	value = value + buffer[index]
	index += 1
	print(f"Value: {value} index: {index}")
	return value

### start here ##
file_path = 'node_06.recv'							# init filename
file_contents = read_file_into_buffer(file_path)	# call read all to buffe
file_size = len(file_contents)						# get file size
if  file_size != correct_file_size:					# check valid file size
	print(f"Invalid file size {file_size} !")
	exit(1)

for i in range(correct_file_size):
	new_value =  get_value(file_contents)			# get native data

print(new_value)

any hint

Regards

Rainer

Well don’t try to extract more values than there are?

1 Like

Yes thats it, thank you

Regards
Rainer

1 Like