Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I sort by track number? #624

Open
kubinka0505 opened this issue Aug 3, 2023 · 1 comment
Open

Can I sort by track number? #624

kubinka0505 opened this issue Aug 3, 2023 · 1 comment
Labels

Comments

@kubinka0505
Copy link

Is it possible to sort existing files list with mutagen with TRCK ID3 tag as the key? Does that module have any available iterators that I could use?

I'm not embedding code since I don't know how to do it. Any ideas?

I mean, I could create dictionary with track number as key and file as value, but I think that there can be some easier solution to this.

@phw phw added the question label Sep 15, 2023
@phw
Copy link
Collaborator

phw commented Sep 15, 2023

Python has the sorted function. If files is a list of mutagen.mp3.MP3 files you could do something like:

def get_tracknumber(file): 
    if trck := file.tags['TRCK']:
        number, total = trck.text[0].split('/')
        try:
            return int(number)
        except ValueError:
            return number

sorted_files = sorted(files, key=get_tracknumber)

Getting the tracknumber from TRCK needs a bit more effort, since according to the ID3 spec this get contain the total number of tracks as well, with track no. and total tracks separated by a slash. Also some people store non-number values in this tag, such as A / B for the sides of Vinyl singles, or track numbers like A1, A2. The above code handles this by returning the number string verbatim in this case.

If you use mutagen.easyid3.EasyID3 you can access the content of TRCK with file['tracknumber'] instead, which simplifies the above code a bit. But you still need to be aware that the total tracks can be part of the tag.

Have a look at https://docs.python.org/3/howto/sorting.html for more details on how to do sorting in Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants