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. >>> fnames = "C:\\dir\\data.ext", "/dir/data.txt", "dir:data" >>> import ntpath, posixpath, macpath >>> def basename(filename): ... for m in ntpath, posixpath, macpath: ... if m.sep in filename: ... return m.basename(filename) ... else: ... # XXX ... raise SomeException('could not do the job') ... >>> for f in fnames: ... 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 -- http://mail.python.org/mailman/listinfo/python-list