Personal tools
You are here: Home Blog Python and Windows file names

Python and Windows file names

Posted by lukepomfrey at Aug 13, 2009 01:35 PM |

Fixing up Windows file names so you can work with them in Python.

I recently did a bit of web design work for a local mobile disco, the site features a simple gallery page, with a section in an admin control panel where the person that runs the site can add pictures.

In the backend, I was using Python's os.path.basename() to obtain the uploaded file name (and prevent directory traversal attacks). I noticed that I was getting files with names like C:\Documents and Settings\User\My Pictures\Picture.jpg in the gallery. Evidently the PTSD resultant from any use of Windows had given me total amnesia over it's utterly terrible directory structure.

Whilst the long file names weren't really a problem, it obviously wasn't very aesthetically pleasing. Thankfully, making things look pretty again was nice and simple, for a file name fname do:

if fname[1] == ":":
    fname = fname[2:]
fname = fname.replace("\\","/")

After that you should end up with a nice *nix looking file name that will cause no problems or general ugliness.

Document Actions
  • Send this
  • Print this
  • Share this
Add comment

You can add a comment by filling out the form below. Plain text formatting.

Info
Note: you are not logged in. You may optionally enter your username and password below. If you don't enter your username and password below, this comment will be posted as the 'Anonymous User'.
(Required)
(Required)