How Pyutube Handles File Naming and Conflicts: A Complete Guide
Pyutube sanitizes YouTube video titles into safe filenames, checks for existing files, and prompts users to rename, overwrite, or cancel when conflicts are detected.
When downloading videos with the hetari/pyutube tool, the application must convert arbitrary video titles into valid filesystem names while avoiding accidental data loss. This article examines the complete flow from title extraction to conflict resolution, referencing the actual implementation in the Pyutube source code.
How Pyutube Generates Safe Filenames
Sanitizing Video Titles with pytubefix
Pyutube delegates initial string cleaning to the pytubefix library. In pyutube/services/FileService.py, the generate_filename method calls pytubefix.helpers.safe_filename to strip unsafe characters from the video title or user-supplied name.
This sanitization removes filesystem-prohibited characters and ensures the base name will not cause write errors on Windows, macOS, or Linux systems.
Constructing the Final Filename
After sanitization, FileService.generate_filename (lines 25-40) assembles the complete filename using the following pattern:
# Pseudocode representation of the logic in FileService.py
filename = f"{sanitized_title}_{media_type}.{extension}"
- Media type: For audio downloads, this value is
"audio"; for video, it uses the selected resolution (e.g.,"720p"). - Extension: Audio files receive
.m4a, while video files use the extension derived from the stream’s MIME type.
This composition ensures every file is self-describing, indicating both its source content and its format.
Handling Playlist Ordering and Prefixes
When downloading playlists with the make_playlist_in_order option enabled, Pyutube prefixes each file with a numeric index to preserve sequence. This logic resides in DownloadService.download_audio and DownloadService.download_video (lines 48-51 and 77-81).
The index is formatted as {index}__ (note the double underscore) and prepended to the base filename generated by FileService. For example, the third video in a playlist might become:
03__My_Video_Title_1080p.mp4
This naming convention allows users to sort downloads chronologically without relying on file metadata.
Detecting and Resolving File Conflicts
Checking for Existing Files
Before initiating any download, Pyutube verifies whether the target path is already occupied. The FileService.is_file_exists method (lines 81-93) performs a straightforward check:
import os
def is_file_exists(self, path: str, filename: str) -> bool:
return os.path.isfile(os.path.join(path, filename))
If this returns True, the download pauses and the conflict resolution workflow begins.
User-Prompted Conflict Resolution
When a collision is detected, FileService.handle_existing_file (lines 41-69) invokes utils.ask_rename_file to present an interactive prompt. Users are presented with three distinct actions:
- Rename – The user inputs a custom title. Pyutube sanitizes this input using the same
safe_filenamelogic and regenerates the filename with the new base. - Overwrite – The original filename is retained, and the existing file will be replaced by the new download.
- Cancel – The application exits immediately, aborting the download.
This manual intervention ensures that no data is destroyed unintentionally, giving users explicit control over their filesystem.
Saving the Final File
Once a unique filename is confirmed, FileService.save_file (lines 11-24) delegates the actual byte retrieval to pytubefix.YouTube.download. It passes the resolved output_path and filename to the underlying library, which handles the HTTP streaming and disk writing.
Summary
- Filename generation occurs in
FileService.generate_filename, which usespytubefix.helpers.safe_filenameto sanitize titles and appends media type and extension metadata. - Playlist ordering adds numeric prefixes via
DownloadServicewhenmake_playlist_in_orderis enabled. - Conflict detection relies on
FileService.is_file_existsto check for existing files before writing. - Resolution strategy prompts users via
FileService.handle_existing_fileto rename, overwrite, or cancel, preventing accidental data loss.
Frequently Asked Questions
How does Pyutube sanitize filenames?
Pyutube delegates string cleaning to pytubefix.helpers.safe_filename, which removes filesystem-prohibited characters from the video title. This sanitized string is then combined with the media type and file extension in FileService.generate_filename to create a safe, valid filename.
What happens if a file already exists during download?
Before writing any data, FileService.is_file_exists checks the target directory. If a collision is detected, FileService.handle_existing_file pauses the download and invokes an interactive prompt, allowing the user to choose between renaming the file, overwriting the existing file, or canceling the operation.
Can Pyutube automatically overwrite existing files?
No, Pyutube does not automatically overwrite files. The conflict resolution workflow requires explicit user confirmation. When a file exists, the user must actively select the "Overwrite" option; otherwise, the download remains paused or is canceled.
How does playlist ordering affect filenames?
When downloading a playlist with the make_playlist_in_order flag enabled, DownloadService prefixes each filename with its numeric index followed by a double underscore (e.g., 01__Video_Title_1080p.mp4). This ensures that files sort chronologically in the filesystem regardless of download completion order.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →