SubRip Subtitle Parser and Writer
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
- gotcha Encountering `UnicodeDecodeError` is common when opening SRT files due to varying encodings. If you face this, try specifying the encoding explicitly, for example, `pysrt.open('file.srt', encoding='iso-8859-1')` or `encoding='utf-8'` if known.
- gotcha The `pysrt` library appears to be minimally maintained, with the last release seven years ago and limited recent activity on its GitHub repository. This may lead to unaddressed bugs or compatibility issues with newer Python versions or complex SRT formats.
- gotcha There is an open issue on the GitHub repository related to problems with the `shift` method and `to_time()` functionality, which could affect precise time manipulations.
Install
-
pip install pysrt
Imports
- pysrt
import pysrt
- open
pysrt.open('file.srt')
Quickstart
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}")