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:
- Set
additional_reserved_names=[".", ".."]. - 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=[".", ".."],
)
)