I've just bought myself a new car-radio (Pioneer DEH-4000UB) with USB key support. And to my great surprise it does not read files from the stick in the sorted (alphabetical) order but "in order as they were written to media". There is a workaround (also noted in the owner's manual), to name the files with 001, 002, 003 prefix. A stupid and time consuming workaround. While looking around if there are any other players with same misfeature, I've noticed that most of them work in the same way (surprisingly, sorting works perfectly when playing music from CD).
... and how does this relate with the post title? Well, I had to write a script that will rename my files so they will comply with Pioneer's "standards". I didn't want to waste my mad PHP skills to do such trivial job, so instead, I've wasted most of Saturday's morning learning Python and produced this script..
Scans folder and all it's sub folders in the location passed on the last line of the script. It checks
ID3v2,
ID3v1 and filename for track numbers and simply prepends 3 characters long numeration in front of every file.
#!/usr/bin/python
import os, re
from ID3 import
from ID3v2 import
def scan_folder(folder):
is_mp3 = re.compile('.*\.mp3$', re.IGNORECASE); files = []
for file in os.listdir(folder):
if os.path.isfile(folder +'/'+ file) and is_mp3.match(file):
files.append(file)
elif os.path.isdir(folder +'/'+ file):
scan_folder(folder +'/'+ file)
if (files):
resort_files(folder, files);
def resort_files(folder, files):
num_check = re.compile('^(\d+)', re.IGNORECASE) tracks = {}; for file in files:
path2file = folder + '/' + file;
track = 0;
while 1:
try:
id3 = ID3v2(path2file)
track = id3.frames['TRCK'].unpack()['Text'];
break;
except:
pass
if ID3(path2file).track:
track = ID3(path2file).track
break;
m = num_check.match(file)
if m:
track = m.group();
break;
# fallback
track = file;
break;
tracks[track] = file;
track_nums = tracks.keys();
track_nums.sort();
num = 1;
for track in track_nums:
os.rename(
folder + '/' + tracks[track],
folder + '/' + str(num).rjust(3, '0') + ' ' + tracks[track]
)
num = num + 1
scan_folder('/dev/null');