Created
September 7, 2023 02:32
-
-
Save uniacid/03bc313d0c5ed4ffbfed0344433f324f to your computer and use it in GitHub Desktop.
Rename torrents to original filename
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
import os | |
import glob | |
import subprocess | |
import sys | |
import shutil | |
import re | |
def install(package): | |
subprocess.check_call([sys.executable, "-m", "pip", "install", package]) | |
try: | |
import torrentool.api | |
except ImportError: | |
install("torrentool") | |
import torrentool.api | |
def sanitize_filename(filename): | |
# Remove any special characters, including single quotes | |
sanitized_name = re.sub(r'[^\w\s.-]', '', filename) | |
return sanitized_name | |
def main(): | |
torrents_folder = input("Enter the path to the folder with torrent files: ") | |
# Define the directory to move renamed torrent files | |
renamed_torrents_folder = os.path.join(torrents_folder, "renamed_torrents") | |
# Ensure the renamed_torrents_folder exists | |
if not os.path.exists(renamed_torrents_folder): | |
os.makedirs(renamed_torrents_folder) | |
torrents_path = os.path.join(torrents_folder, "*.torrent") | |
for torrent_file in glob.glob(torrents_path): | |
try: | |
torrent = torrentool.api.Torrent.from_file(torrent_file) | |
if torrent and torrent.name: | |
# Sanitize the torrent name to remove special characters | |
sanitized_name = sanitize_filename(torrent.name) | |
# Replace spaces and dashes in torrent names with underscores | |
new_torrent_name = sanitized_name.replace(" ", "_").replace("-", "_") + ".torrent" | |
# Move the renamed torrent file to the renamed_torrents directory | |
destination_path = os.path.join(renamed_torrents_folder, new_torrent_name) | |
shutil.move(torrent_file, destination_path) | |
print(f"Renamed '{torrent_file}' to '{destination_path}'") | |
else: | |
print(f"Could not rename '{torrent_file}' as the torrent name is missing.") | |
except Exception as e: | |
print(f"Error processing '{torrent_file}': {e}") | |
print("-----------------") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment