Skip to content

Instantly share code, notes, and snippets.

@puntonim
Last active October 20, 2025 13:03
Show Gist options
  • Select an option

  • Save puntonim/c07d01a4c7196abaf627915d9a32b8e8 to your computer and use it in GitHub Desktop.

Select an option

Save puntonim/c07d01a4c7196abaf627915d9a32b8e8 to your computer and use it in GitHub Desktop.
Randomize songs order
#!/usr/local/bin/python3
"""
GOAL: randomize the order of songs in this dir, as played by AGPTEK A26.
Note: the order is not determined by file names!!
The player AGPTEK A26 plays songs following the FAT directory entry order,
like many basic devices do.
Which basically is the timestamp a file was added to the dir:
https://superuser.com/a/1348720
Steps:
- collect all songs in this root dir
- randomize their order
- move songs to a temporary subdir
- move songs back to the original root dir with the new order
IMP: the number at the beginning of file names (eg. "003 ACDC - Highway to Hell.mp3")
is not what the player uses to determine the order!! It just makes the order
more human-readable.
Note: the player also supports playlists, but I prefer to use the regular "Folder view" feature.
"""
import random
import shutil
from collections import namedtuple
from os import listdir, makedirs, rename
from os.path import isfile, join
from pathlib import Path
CUR_DIR = Path(__file__).parent
songs = list()
def main():
# Collect all songs in a list.
for f in listdir(CUR_DIR):
f = CUR_DIR / f
if isfile(CUR_DIR / f):
if f.suffix.lower() not in (".mp3", ".m4a") or f.name.startswith("."):
continue
songs.append(f)
# Randomize the list.
random.shuffle(songs)
tmp_dir = CUR_DIR / "TMP"
if tmp_dir.exists():
try:
tmp_dir.rmdir()
except Exception as exc:
raise Exception("You should delete the dir TMP manually as it is not empty") from exc
makedirs(tmp_dir, exist_ok=False)
# Rename the songs and move them to the tmp dir.
for i, song in enumerate(songs):
# Start from 1.
i += 1
# Strip out the numbering (eg. "005") from the song name.
old_name = song.name
try:
int(old_name[:4])
old_name = song.name[4:]
except ValueError:
pass
new_name = f"{i:03d} {old_name}"
# Rename and move to TMP dir.
rename(CUR_DIR / song.name, tmp_dir / new_name)
# Move all the songs back to the original dir.
for f in listdir(tmp_dir):
shutil.move(tmp_dir / f, CUR_DIR)
# Finally delete the tmp dir.
tmp_dir.rmdir()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment