making a valid file name...

Tim Chase python.list at tim.thechases.com
Tue Oct 17 13:14:10 EDT 2006


> Sometimes the user inputs characters that aren't valid 
> characters for a file or directory name. Here are the
> characters that I consider to be valid characters...
> 
> valid =
> ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '

Just a caveat, as colons and slashes can give grief on various 
operating systems...combined with periods, it may be possible to 
cause trouble too...

> This is what I have:
> 
> def fixfilename(fname):
> 	valid =
> ':.\,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
> 	for i in range(len(fname)):
> 		if valid.find(fname[i]) < 0:
> 			fname[i] = ' '
>        return fname
> 
> Anyone think of a simpler solution?

I don't know if it's simpler, but you can use

 >>> fname = "this is a test & it ain't expen$ive.py"
 >>> ''.join(c in valid and c or ' ' for c in fname)
'this is a test   it ain t expen ive.py'

It does use the "it's almost a ternary operator, but not quite" 
method concurrently being discussed/lambasted in another thread. 
  Treat accordingly, with all that may entail.  Should be good in 
this case though.

If you're doing it on a time-critical basis, it might help to 
make "valid" a set, which should have O(1) membership testing, 
rather than using the "in" test with a string.  I don't know how 
well the find() method of a string performs in relationship to 
"in" testing of a set.  Test and see, if it's important.

-tkc






More information about the Python-list mailing list