[SOLVED] Python MacOS Loop Files Get File Info

Issue

This Content is from Stack Overflow. Question asked by Jorge

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() 



Solution

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(".")
data = None
for filename in root_directory.rglob("*.mp3"):
    mp3data = eyed3.load(filename)
    if mp3data.tag != None:
        print(mp3data.tag.artist)
    print(mp3data.info.time_secs)


This Question was asked in StackOverflow by Jorge and Answered by rasjani It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?