making a valid file name...
Matthew.Warren at Digica.com
Wed Oct 18 11:13:12 CEST 2006
> Hi I'm writing a python script that creates directories from user
> 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?
>>> import re
>>> valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
>>> goodfilename=re.sub('[^'+valid+']',' ',badfilename)
' ^ ^ ^ihgeroighroeig3645^ ^ knovin98u4 346 1461461'
This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer.
You should not copy the email, use it for any purpose or disclose its contents to any other person.
Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
More information about the Python-list