Search code examples
pythonfileiopathmidi

OS Error file path and name being changed without user interference


I am trying to read a midi file in the following manner using an in-built function from the library - mido to read such files.

mid = mido.MidiFile('..\Datasets\abel.mid')

Error:

OSError                                   Traceback (most recent call last)
<ipython-input-34-5c67b78f0caf> in <module>()
----> 1 mid = mido.MidiFile('F:\AI\Music classification\Datasets\abel.mid')

~\Anaconda3\lib\site-packages\mido\midifiles\midifiles.py in __init__(self, filename, file, type, ticks_per_beat, charset, debug, clip)
    313             self._load(file)
    314         elif self.filename is not None:
--> 315             with io.open(filename, 'rb') as file:
    316                 self._load(file)
    317 

OSError: [Errno 22] Invalid argument: '..\\Datasets\x07bel.mid'

If we observe the last line of the error, we notice that the file name seems to have been changed. Why does this happen?

If I change the code in the following manner by adding an extra \wherever the file name seems to have been changed, then the file is read perfectly:

mid = mido.MidiFile('..\Datasets\\abel.mid')

Why is it that when I add an extra \, the code works?


Solution

  • Python uses backslash for string escapes - which lets you define different values for a character sequence. Just as \n is a newline, \a is the hex byte 07. You can escape the backslash itself, so \\ is just a backslash. And you can use "raw" strings (e.g., `r"\a") to disable escaping all together.