Skip to content

Instantly share code, notes, and snippets.

@luckylittle
Created June 12, 2025 11:12
Show Gist options
  • Save luckylittle/45b27176c3efef0ea73f93f8987470ff to your computer and use it in GitHub Desktop.
Save luckylittle/45b27176c3efef0ea73f93f8987470ff to your computer and use it in GitHub Desktop.
Python script, uses mkbrr to rename files from .session folder
import os
import subprocess
import re
from collections import defaultdict
# Directory containing the .torrent files like 534DB1275682C6F5CFC5EE0C10D414B84CB84BC4.torrent
torrent_dir = "~/Downloads"
# Map to track name collisions
name_counts = defaultdict(int)
def sanitize_filename(name):
# Remove or replace characters that are not valid in filenames
return re.sub(r'[<>:"/\\|?*]', '_', name)
def get_name_from_mkbrr(filepath):
try:
result = subprocess.run(["mkbrr", "inspect", filepath], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for line in result.stdout.splitlines():
if line.startswith(" Name:"):
return line.split(":", 1)[1].strip()
except Exception as e:
print(f"Error inspecting file {filepath}: {e}")
return None
def main():
for filename in os.listdir(torrent_dir):
if not filename.lower().endswith(".torrent"):
continue
full_path = os.path.join(torrent_dir, filename)
name = get_name_from_mkbrr(full_path)
if not name:
print(f"Skipping {filename} - name not found")
continue
sanitized_name = sanitize_filename(name)
base_name = sanitized_name
count = name_counts[base_name]
while True:
new_filename = f"{base_name}.torrent" if count == 0 else f"{base_name}_{count}.torrent"
new_path = os.path.join(torrent_dir, new_filename)
if not os.path.exists(new_path):
break
count += 1
# Update count for the base name
name_counts[base_name] = count + 1
# Rename the file
try:
os.rename(full_path, new_path)
print(f"Renamed: {filename} → {new_filename}")
except Exception as e:
print(f"Error renaming {filename} to {new_filename}: {e}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment