Check if a filename is valid

Issue

What would be the most conservative way to check if a file-name is valid in Python on all platforms (including mobile platforms like Android, iOS)?

Ex.

this_is_valid_name.jpg -> Valid

**adad.jpg -> Invalid

a/ad -> Invalid

Solution

The most harsh way to check if a file would be a valid filename on you target OSes is to check it against a list of properly tested filenames.

valid = myfilename in ['this_is_valid_name.jpg']

Expanding on that, you could define a set of characters that you know are allowed in filenames on every platform :

valid = set(valid_char_sequence).issuperset(myfilename)

But this is not going to be enough, as some OSes have reserved filenames.

You need to either exclude reserved names or create an expression (regexp) matching the OS allowed filename domain, and test your filename against that, for each target platform.

AFAIK, Python does not offer such helpers, because it’s Easier to Ask Forgiveness than Permission. There’s a lot of different possible combinations of OSes/filesystems, it’s easier to react appropriately when the os raises an exception than to check for a safe filename domain for all of them.

Answered By – ddelemeny

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published