os.path.basename() - only Windows OR *nix?

T

Thomas Ploch

Hello,

I have a cgi script that handles fileuploads from windows and *nix
machines. i need os.path.basename(filename) to get the pure filename.

For *nix, thats not a problem, but for windows, it always returns the
full path:



#/usr/bin/env python

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()
filename = os.path.basename(form['uploadfile'].filename)

print 'Content-Type: text/html\n\n'
print filename



-----------------

For 'C:\text\text.txt', the output is 'C:\text\text.txt', which should
be 'text.txt', the same happens for 'C:\\text\\text.txt'. I think its
the escapes that makes python not splitting it. All Unix style paths get
converted the right way.

Is there an easy way around this, or do I really have to write a parser
including _all_ Python escapes?

Thomas
 
B

Bruno Desthuilliers

Thomas Ploch a écrit :
Hello,

I have a cgi script that handles fileuploads from windows and *nix
machines. i need os.path.basename(filename) to get the pure filename.

For *nix, thats not a problem, but for windows, it always returns the
full path:



#/usr/bin/env python

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()
filename = os.path.basename(form['uploadfile'].filename)

print 'Content-Type: text/html\n\n'
print filename



-----------------

For 'C:\text\text.txt', the output is 'C:\text\text.txt', which should
be 'text.txt', the same happens for 'C:\\text\\text.txt'. I think its
the escapes that makes python not splitting it. All Unix style paths get
converted the right way.

Let me guess : your cgi script is running on *n*x ?-)
Is there an easy way around this,
Probably.
.... for m in ntpath, posixpath, macpath:
.... if m.sep in filename:
.... return m.basename(filename)
.... else:
.... # XXX
.... raise SomeException('could not do the job')
........ print f, basename(f)
....
C:\dir\data.ext data.ext
/dir/data.txt data.txt
dir:data data
Might need some improvements, but you get the idea...

HTH
 
T

Thomas Ploch

Bruno said:
Let me guess : your cgi script is running on *n*x ?-)

Pretty hard to get this one, heh? :-D
Probably.

Good that you decided I was worth the information.
... for m in ntpath, posixpath, macpath:
... if m.sep in filename:
... return m.basename(filename)
... else:
... # XXX
... raise SomeException('could not do the job')
...
... print f, basename(f)
...
C:\dir\data.ext data.ext
/dir/data.txt data.txt
dir:data data

Thnaks a lot. :)

Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top