From f851fdcafe2fd86be5a098b4f3936c4bfd97188b Mon Sep 17 00:00:00 2001 From: Keith Edmunds Date: Mon, 22 Aug 2022 16:08:24 +0100 Subject: [PATCH] First draft of rename_singles.py --- app/rename_singles.py | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100755 app/rename_singles.py diff --git a/app/rename_singles.py b/app/rename_singles.py new file mode 100755 index 0000000..58f116a --- /dev/null +++ b/app/rename_singles.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Script to manage renaming existing files in given directory and +# propagating that change to database. Typical usage: renaming files +# from 'title.mp3' to title - artist.mp3' +# +# Actions: +# +# - record all filenames and inode numbers +# - external: rename the files +# - update records with new filenames for each inode number +# - update external database with new paths + +import os +import sqlite3 + +PHASE = 2 + +# Check file of same name exists in parent directory +source_dir = '/home/kae/tmp/Singles' # os.getcwd() +db = "/home/kae/tmp/singles.sqlite" + + +def main(): + with sqlite3.connect(db) as connection: + cursor = connection.cursor() + if PHASE == 1: + cursor.execute( + "CREATE TABLE IF NOT EXISTS mp3s " + "(inode INTEGER, oldname TEXT, newname TEXT)" + ) + + for fname in os.listdir(source_dir): + fullpath = os.path.join(source_dir, fname) + inode = os.stat(fullpath).st_ino + sql = f'INSERT INTO mp3s VALUES ({inode}, "{fname}", "")' + cursor.execute(sql) + + if PHASE == 2: + for fname in os.listdir(source_dir): + fullpath = os.path.join(source_dir, fname) + inode = os.stat(fullpath).st_ino + sql = ( + f'UPDATE mp3s SET newname = "{fname}" WHERE inode={inode}' + ) + try: + cursor.execute(sql) + except sqlite3.OperationalError: + print(f"Error with {inode} -> {fname}") + + cursor.close() + + +main()