How to check if a path *could* be a legal path?
peter at engcorp.com
Tue Apr 20 16:41:08 CEST 2004
Maciej Sobczak wrote:
> I have a string.
> This string is to be used as a path for a new file.
> I would like to check if this string *could be* a valid file name,
> *before* I try to create the file itself.
> In other words, I would like to know whether some string violates the
> underlying OS's policies (or maybe some more restriced policies, but
> portable) considering file paths.
> Does the Python library contain a functionality that allows to achieve
> this goal?
I don't think it does, and certainly not in a cross-platform manner.
Furthermore, even on a given platform I suspect you will not find
such a thing, because there are things like remote file systems
which might change the rules. One file system might recognize
more or fewer valid characters than another, even on the same OS.
The best is probably just to define a restrictive subset of
possible characters and do a simple regular expression which
handles the basic path separator stuff, maybe with a little
os.path.sep substituted on the fly to keep it relatively
Presumably this isn't a case where you can just catch an exception
at the time file creation is attempted? After all, even with
a valid file name, you could still have several types of error
at the moment of creation.
More information about the Python-list