Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a filename is valid

Tags:

python

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

like image 671
gat Avatar asked Mar 13 '14 21:03

gat


People also ask

How do I make a file name valid?

Illegal Filename CharactersDon't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.

What is valid file name?

Supported characters for a file name are letters, numbers, spaces, and ( ) _ - , . *Please note file names should be limited to 100 characters. Characters that are NOT supported include, but are not limited to: @ $ % & \ / : * ? " ' < > | ~ ` # ^ + = { } [ ] ; !

Why is not a valid file name?

'FileName is not valid': while creating and saving, or opening an Excel file such error may mean one of the following reason: Path of file including file name may exceed 218 number of characters limit. The file name may be incorrect. The path may not be appropriate.


1 Answers

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.

like image 81
ddelemeny Avatar answered Sep 28 '22 09:09

ddelemeny