Python Script

A Python Script to Batch Edit Subtitle Files

This is a powerful utility script for anyone who works with subtitle files. It automates the process of removing specific, unwanted sentences (like advertisements, credits, or common annotations) from multiple .srt subtitle files simultaneously. The script searches through an entire folder, including all its subfolders, and creates cleaned versions of your files, leaving your originals untouched.

How to Use This Script

  1. Save the Script: Click "Copy Script" below and save the code as `srt_sentence_deleter.py`.
  2. Organize Your Files: Place all the `.srt` files you wish to edit into a single parent folder. The script will find all of them.
  3. Run from Terminal: Open your terminal, navigate to the script's directory, and run it with the command: python srt_sentence_deleter.py
  4. Follow the Prompts: The script will ask for the path to your SRT folder and the exact sentences you want to delete. You can enter multiple sentences separated by a semicolon (e.g., `Synced by John Doe; Subtitles from www.example.com`).
  5. Find Your Clean Files: A new folder named "updated" will appear in your original folder, containing all the modified subtitle files.

import os

def delete_sentences_in_srt_files():
    source_directory = input("Enter the path to the folder containing .srt files: ")

    if not os.path.isdir(source_directory):
        print(f"Error: Directory '{source_directory}' not found.")
        return

    sentences_to_delete_input = input(
        "Enter sentences to delete (separate with a semicolon ';'): "
    )
    sentences_to_delete = [s.strip() for s in sentences_to_delete_input.split(';') if s.strip()]

    if not sentences_to_delete:
        print("No sentences to delete were provided. Exiting.")
        return

    print(f"\nSentences to delete: {sentences_to_delete}")
    print("\nStarting file processing...")
    updated_files_count = 0

    for root, _, files in os.walk(source_directory):
        for filename in files:
            if filename.lower().endswith(".srt"):
                filepath = os.path.join(root, filename)
                print(f"Processing: {filepath}")

                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        content = f.read()

                    original_content = content
                    for sentence in sentences_to_delete:
                        content = content.replace(sentence, '')

                    if content != original_content:
                        relative_path = os.path.relpath(root, source_directory)
                        updated_subfolder_path = os.path.join(source_directory, "updated", relative_path)
                        os.makedirs(updated_subfolder_path, exist_ok=True)
                        output_filepath = os.path.join(updated_subfolder_path, filename)

                        with open(output_filepath, 'w', encoding='utf-8') as f:
                            f.write(content)
                        print(f"  -> Updated and saved to: {output_filepath}")
                        updated_files_count += 1
                    else:
                        print("  -> No changes needed.")

                except Exception as e:
                    print(f"  -> Error processing {filepath}: {e}")

    print(f"\nProcessing complete. {updated_files_count} files were updated.")

if __name__ == "__main__":
    delete_sentences_in_srt_files()