Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic way to check validity of file name in Python?

Creating a file can fail in Python because of various file name related reasons:

  1. the file path is too long (see e.g.: what-is-the-maximum-length-of-a-file-path-in-ubuntu )
  2. the file name may be too long, as the file system is encrypted – see e.g. comment in answer to that question:
On encrypted filesystems the max filename length is 143 bytes. 
To decide whether a filename is short enough you can find his byte length in Python 
with len(filename.encode()). – 

Marvo
Mar 9, 2018 at 12:45
  1. there are characters that either make issues in the file system, are not recommended or could make issues in another file system like:  \n!@#$%^&*()[]{};:,/<>?\|~=+`

  2. … .

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

Is there any convenience function that tells me beforehand whether

  • a) my file name will work
  • b) may lead to issues in other file systems
  • c) and why it will fail?

Solutions like:
Check whether a path is valid in Python without creating a file at the path's target
or
Validate a filename in python

unfortunately do not fulfill the requirements a) – c) (even the first one does not recognize the 143 character restrictions for encrypted folders / drives)

>Solution :

If external package are allowed I suggest you try pathvalidate, function validate_filename should be of interest if you need to find why it will fail? whilst is_valid_filename if you need to find if file name will work

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading