Python MacOS Loop Files Get File Info

Question:

I am trying to loop through all mp3 files in my directory in MacOS Monterrey and for every iteration get the file’s more info attributes, like Title, Duration, Authors etc. I found a post saying use xattr, but when i create a variable with xattr it doesn’t show any properties or attributes of the files. This is in Python 3.9 with xattr package

import os
import xattr
directory = os.getcwd()
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    # checking if it is a file
    if os.path.isfile(f):
        print(f)
        x = xattr.xattr(f)
        xs = x.items() 
Asked By: Jorge

||

Answers:

xattr is not reading mp3 metadata or tags, it is for reading metadata that is stored for the particular file to the filesystem itself, not the metadata/tags thats stored inside the file.

In order to get the data you need, you need to read the mp3 file itself with some library that supports reading ID3 of the file, for example: eyed3.

Here’s a small example:

from pathlib import Path
import eyed3

root_directory = Path(".")
for filename in root_directory.rglob("*.mp3"):
    mp3data = eyed3.load(filename)
    if mp3data.tag != None:
        print(mp3data.tag.artist)
    print(mp3data.info.time_secs)
Answered By: rasjani