SubRip Subtitle Parser and Writer

1.1.2 · maintenance · verified Mon Apr 13

pysrt is a Python library for parsing, modifying, and composing SubRip (.srt) subtitle files. It allows developers to read SRT files, manipulate subtitle text and timing, and save changes. The current version is 1.1.2. The library appears to have a slow release cadence, with the last release being seven years ago and minimal recent development activity on its GitHub repository.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to open an SRT file, access and modify individual subtitle items, shift the timings of all subtitles, and save the changes to a new file. It includes a basic example of creating a dummy SRT file and then cleaning it up.

import pysrt
import os

# Create a dummy SRT file for demonstration
dummy_srt_content = '''1
00:00:00,500 --> 00:00:02,500
Hello world!

2
00:00:03,000 --> 00:00:05,000
This is a test subtitle.'''

file_path = 'example.srt'
with open(file_path, 'w', encoding='utf-8') as f:
    f.write(dummy_srt_content)

# Parse the SRT file
try:
    subs = pysrt.open(file_path)
    print(f"Loaded {len(subs)} subtitles.")

    # Access and modify a subtitle item
    first_sub = subs[0]
    print(f"Original first subtitle: {first_sub.text}")
    first_sub.text = "Modified first subtitle!"
    print(f"Modified first subtitle: {first_sub.text}")

    # Shift all subtitles by 1 second forward
    subs.shift(seconds=1)
    print(f"First subtitle start time after shift: {first_sub.start}")

    # Save the modified subtitles to a new file
    output_file_path = 'example_modified.srt'
    subs.save(output_file_path, encoding='utf-8')
    print(f"Modified subtitles saved to {output_file_path}")

    # Clean up dummy files
    os.remove(file_path)
    os.remove(output_file_path)

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →