Created
June 8, 2023 11:07
-
-
Save tarneaux/7ae60e9d8d1b23e09794f33621e3c35b to your computer and use it in GitHub Desktop.
Reorder an m3u playlist with fzf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Reorder m3u playlist files with fzf | |
import os | |
import sys | |
import subprocess | |
from time import sleep | |
# Get the path to the m3u file | |
if len(sys.argv) == 2: | |
path = sys.argv[1] | |
else: | |
print("Usage: reorder_m3u.py <m3u path>") | |
sys.exit(1) | |
try: | |
with open(path, 'r') as f: | |
lines = [line.strip() for line in f.readlines()[2:]] | |
except FileNotFoundError: | |
print("File not found") | |
sys.exit(1) | |
# Get the song list | |
song_list = [] | |
i = 0 | |
while i < len(lines): | |
if lines[i].startswith("#EXTINF:"): | |
song_list.append((lines[i], lines[i+1])) | |
i += 2 | |
else: | |
i += 1 | |
# Get the new order of the playlist | |
new_order = [] | |
for i in range(len(lines)): | |
# Get the next song with fzf | |
fzf_input = "\n".join([song[1] for song in song_list]).encode() | |
fzf = subprocess.run(["fzf", "--prompt", "Song: "], input=fzf_input, stdout=subprocess.PIPE) | |
if fzf.returncode != 0: | |
print(new_order) | |
print("status non-zero, exiting") | |
break | |
song = fzf.stdout.decode().strip() | |
# Find the song in the list | |
for j in range(len(song_list)): | |
if song_list[j][1].strip() == song: | |
new_order.append(song_list[j]) | |
del song_list[j] | |
break | |
if len(song_list) == 0: | |
break | |
# Write the new playlist | |
with open("output.m3u", 'w') as f: | |
f.write("#EXTM3U\n") | |
for song in new_order: | |
f.write(song[0] + "\n") | |
f.write(song[1] + "\n") | |
f.write("\n") | |
print("Playlist written to output.m3u") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment