pathvalidate

repository·master·Indexed 43 days ago

https://github.com/thombashi/pathvalidate

A Python library for sanitizing and validating strings for use as filenames or file paths across multiple platforms, including Linux, Windows, macOS, POSIX, and universal. It provides functions like sanitize_filename(), validate_filepath(), and is_valid_filename() to ensure path compatibility and handle reserved system names.

Tokens
5.7K
Snippets
27
Records
38
Agent score
54%

What's inside pathvalidate

  1. Handle dot directory entries ('.' and '..')

    master

    By default, pathvalidate excludes the special directory entries . (current directory) and .. (parent directory) from reserved-name checks in both validate_* and sanitize_* functions. This is because these names appear frequently in real-world relative paths.

    If your application requires treating . and .. as reserved names (i.e., you want to reject or sanitize them), you must explicitly pass them using the additional_reserved_names=[".", ".."] argument.

  2. Install pathvalidate

    master

    You can install pathvalidate using pip, conda, or apt.

    Using pip:

    pip install pathvalidate

    Using conda:

    conda install conda-forge::pathvalidate

    Using apt:

    sudo add-apt-repository ppa:thombashi/ppa
    sudo apt update
    sudo apt install python3-pathvalidate
    pip install pathvalidate
  3. Sanitize dot directory entries

    master

    By default, sanitize_filename does nothing to . and .., while sanitize_filepath normalizes them (e.g., hoge/./foo becomes hoge/foo).

    To replace . and .. using a reserved_name_handler (similar to how other reserved words are handled), you must:

    1. Set additional_reserved_names=[".", ".."].
    2. For sanitize_filepath, set normalize=False to prevent the default path normalization from removing the entries before the handler can process them.
    from pathvalidate import sanitize_filepath, sanitize_filename
    from pathvalidate.error import ValidationError
    
    
    def always_add_trailing_underscore(e: ValidationError) -> str:
        if e.reusable_name:
            return e.reserved_name
    
        return f"{e.reserved_name}_"
    
    # Sanitize filename: '.' becomes '._'
    print(
        sanitize_filename(
            ".",
            reserved_name_handler=always_add_trailing_underscore,
            additional_reserved_names=[".", ".."],
        )
    )
    
    # Sanitize filepath: 'hoge/./foo' becomes 'hoge/._/foo'
    print(
        sanitize_filepath(
            "hoge/./foo",
            normalize=False,
            reserved_name_handler=always_add_trailing_underscore,
            additional_reserved_names=[".", ".."],
        )
    )
  4. Sanitize a filepath with sanitize_filepath()

    master

    Use sanitize_filepath() to clean a string so it can be safely used as a file path. This function replaces invalid characters for a filepath within the argument, ensuring the path is valid for the underlying filesystem.

    from pathvalidate import sanitize_filepath
    
    filepath = "/path/to/invalid/file*name?.txt"
    sanitized_filepath = sanitize_filepath(filepath)
    print(sanitized_filepath)  # Output: "/path/to/invalid/file_name_.txt" (exact output depends on implementation)
  5. Validate a file path with validate_filepath()

    master

    Use the validate_filepath() function to check if a string is a valid file path. If the path contains characters or structures that are invalid for a file path, the function will raise a ValueError.

    from pathvalidate import validate_filepath
    
    try:
        validate_filepath("/valid/path/to/file.txt")
        print("File path is valid")
    except ValueError:
        print("File path is invalid")
    
    try:
        validate_filepath("/invalid\?path/to/file.txt")
        print("File path is valid")
    except ValueError:
        print("File path is invalid")
  6. Sanitize a filename with sanitize_filename()

    master

    Use sanitize_filename() to clean a string so it can be safely used as a filename. This function replaces invalid characters within the provided argument with a safe alternative.

    from pathvalidate import sanitize_filename
    
    filename = "invalid/file*name?.txt"
    sanitized_filename = sanitize_filename(filename)
    print(sanitized_filename)  # Output: "invalid_file_name_.txt" (exact output depends on implementation)