pythonfilenames

Elegant way in python to make sure a string is suitable as a filename?


I want to use a user-provided string as a filename for exporting, but have to make sure that the string is permissible on my system as a filename. From my side it would be OK to replace any forbidden character with e.g. '_'.

Here I found a list of forbidden characters for filenames.

It should be easy enough to use the str.replace() function, I was just wondering if there is already something out there that does that, potentially even taking into account what OS I am on.


Solution

  • pathvalidate is a Python library to sanitize/validate a string such as filenames/file-paths/etc.

    This library provides both utilities for validation of paths:

    import sys
    from pathvalidate import ValidationError, validate_filename
    
    try:
        validate_filename("fi:l*e/p\"a?t>h|.t<xt")
    except ValidationError as e:
        print("{}\n".format(e), file=sys.stderr)
    

    And utilities for sanitizing paths:

    from pathvalidate import sanitize_filename
    
    fname = "fi:l*e/p\"a?t>h|.t<xt"
    print("{} -> {}".format(fname, sanitize_filename(fname)))