making a valid file name...

Jon Clements joncle at googlemail.com
Tue Oct 17 18:36:40 CEST 2006


SpreadTooThin wrote:

> Hi I'm writing a python script that creates directories from user
> input.
> 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 '
>
> if I have a string called fname I want to go through each character in
> the filename and if it is not a valid character, then I want to replace
> it with a space.
>
> 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?

If you want to strip 'em:

>>> valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
>>> filename = '!"£!£$"$££$%$£%$£lasfjalsfjdlasfjasfd()()()somethingelse.dat'
>>> stripped = ''.join(c for c in filename if c in valid)
>>> stripped
'lasfjalsfjdlasfjasfdsomethingelse.dat'

If you want to replace them with something, be careful of the regex
string  being built (ie a space character).
import re
>>> re.sub(r'[^%s]' % valid,' ',filename)
'                 lasfjalsfjdlasfjasfd      somethingelse.dat'


Jon.




More information about the Python-list mailing list