Sorrells Sorrells - 3 months ago 11
Python Question

How do i get each byte into a list

I want to open a MIDI file and analyse each byte. But i am VERY unfamiliar with handeling bytes and bits. Midi's are written in hexadecimal if that does any difference.

What i want to do is put each byte into a list, and then make a for loop to check each one. How would i go about doing that?

I've come this far (which isn't very far):

# Open MIDI file
mFile = open("test.mid", 'rb')

# Checks if file is MIDI
hChunk = mFile.read(4)
if hChunk != b'MThd':
raise ValueError('Not a MIDI file')

print(mFile.read())


Also if anyone has any easy to understand MIDI format explanation links, that would be appreciated! :)

Answer

just completed your code to scan the first 40 bytes of data. It prints the decimal value as well as the hex value using both C-like % formatting and more pythonic format method, which may be more understandable if format specification is in hex.

midi file has been downloaded here and saved in the directory of the script (hence the strange __file__ stuff to compute proper dir when testing)

import os

# Open MIDI file
mFile = open(os.path.join(os.path.dirname(__file__),"MIDI_sample.mid"), 'rb')

# Checks if file is MIDI
hChunk = mFile.read(4)
if hChunk != b'MThd':
    raise ValueError('Not a MIDI file')

contents = mFile.read()
mFile.close()

total_len = len(contents)

for i in range(0,40):
    print(contents[i],"x%02X"% contents[i],"x{:02X}".format(contents[i]))