get lenght of mp3 in a folder using mutagen

Viewed 222

I made this code to get the duration of all the mp3 files in a folder, but it gives me an error:

import os
from mutagen.mp3 import MP3

path = "D:/FILE/P. F. Ford - A Body on the Beach/"

filenames = next(os.walk(path, topdown=True))
for filename in filenames:
    audio = MP3(filename)
    print(audio.info.length)

the error:

Traceback (most recent call last):
  File "C:\Desktop\.venv\lib\site-packages\mutagen\_util.py", line 251, in _openfile
    fileobj = open(filename, "rb+" if writable else "rb")
PermissionError: [Errno 13] Permission denied: 'D:/FILE/P. F. Ford - A Body on the Beach/'

i have all the permissions, can you point me to the right path?

2 Answers

You're error occur due to the wrong filenames when you get filenames from your code line

filenames = next(os.walk(path, topdown=True))

Then you get all types (extensions) of files that are present in that folder. So, you need to filter these files only *.mp3 files, and then re-run your code.

I have solved my question by this code i adapted:

import os
from mutagen.mp3 import MP3

path = "D:/FILE/P. F. Ford - A Body on the Beach"


def convert(seconds):
    hours = seconds // 3600
    seconds %= 3600
    mins = seconds // 60
    seconds %= 60
    return(hours, mins, seconds)


for root, dirs, files in os.walk(os.path.abspath(path)):
    for file in files:
        if file.endswith(".mp3"):
            print(os.path.join(root, file))
            audio = MP3(os.path.join(root, file))
            # print(audio.info.length)
            hours, mins, seconds = convert(audio.info.length)
            print(str(int(hours)) + ":" +
                  str(int(mins)) + ":" + str(int(seconds)))
Related