Randomly ordering files in a directory with python
I have a playlist file which contains audio files to play. The audio player unfortunately plays the music files in a sequential order, in whatever order they are listed in the playlist file. So occasionally I have to regenerate the playlist file to randomize the audio files order. Here is a simple script that I had to write for this purpose, the core component is the random.shuffle(list) python function –
Create script file as shuffle_files.py –
#!/usr/bin/env python import os import random import sys music_files=[] if len(sys.argv) != 2: print "Usage:", sys.argv[0], "/path/directory" else: dir_name=sys.argv[1] if os.path.isdir(dir_name): for file_name in os.listdir(dir_name): music_files.append(file_name) else: print "Directory", dir_name, "does not exist" sys.exit(1) # shuffle list random.shuffle(music_files) for item in music_files: print os.path.join(dir_name,item)
Run the script by providing a path to a directory with files. Each iteration should list the files in the directory in a different order.
Note – the script does not recurse into the directories, it can be easily modified with os.walk if necessary.
root@svm1010:/home/daniel/scripts# python shuffle_files.py /opt/iotop/iotop /opt/iotop/iotop/setup.py /opt/iotop/iotop/README /opt/iotop/iotop/iotop /opt/iotop/iotop/iotop.8 /opt/iotop/iotop/NEWS /opt/iotop/iotop/iotop.py /opt/iotop/iotop/PKG-INFO /opt/iotop/iotop/THANKS /opt/iotop/iotop/sbin /opt/iotop/iotop/setup.cfg /opt/iotop/iotop/ChangeLog /opt/iotop/iotop/.gitignore /opt/iotop/iotop/COPYING root@svm1010:/home/daniel/scripts# python shuffle_files.py /opt/iotop/iotop /opt/iotop/iotop/PKG-INFO /opt/iotop/iotop/COPYING /opt/iotop/iotop/iotop /opt/iotop/iotop/setup.cfg /opt/iotop/iotop/NEWS /opt/iotop/iotop/README /opt/iotop/iotop/.gitignore /opt/iotop/iotop/setup.py /opt/iotop/iotop/THANKS /opt/iotop/iotop/iotop.py /opt/iotop/iotop/ChangeLog /opt/iotop/iotop/iotop.8 /opt/iotop/iotop/sbin root@svm1010:/home/daniel/scripts# python shuffle_files.py /opt/iotop/iotop /opt/iotop/iotop/THANKS /opt/iotop/iotop/setup.py /opt/iotop/iotop/NEWS /opt/iotop/iotop/README /opt/iotop/iotop/iotop.8 /opt/iotop/iotop/.gitignore /opt/iotop/iotop/ChangeLog /opt/iotop/iotop/sbin /opt/iotop/iotop/PKG-INFO /opt/iotop/iotop/iotop /opt/iotop/iotop/COPYING /opt/iotop/iotop/iotop.py /opt/iotop/iotop/setup.cfg
Reference – https://docs.python.org/2/library/random.html?highlight=shuffle#random.shuffle