# 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.**

- Repository: [Ebraheem Alhetari/pyutube](https://github.com/hetari/pyutube)
- Tags: 
- Published: 2026-03-03

---

**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`](https://github.com/hetari/pyutube/blob/main/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:

```python

# 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:

```python
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_filename` logic 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 uses `pytubefix.helpers.safe_filename` to sanitize titles and appends media type and extension metadata.
- **Playlist ordering** adds numeric prefixes via `DownloadService` when `make_playlist_in_order` is enabled.
- **Conflict detection** relies on `FileService.is_file_exists` to check for existing files before writing.
- **Resolution strategy** prompts users via `FileService.handle_existing_file` to 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.