Filepath string manipulation help

qwweeeit at yahoo.it qwweeeit at yahoo.it
Thu Nov 3 10:36:53 EST 2005


Hi mjakowlew,
to get file basename in Linux I use simply:
filepath.split('/')[-1]
But in Windows, being the dir separator '\',
you get into trouble if the dir or file name begins
with one of the "escape sequences":
  \a  ASCII Bell            (BEL) \x07
  \b  ASCII Backspace       (BS)  \x08
  \f  ASCII Formfeed        (FF)  \x0c
  \n  ASCII Linefeed        (LF)
  \r  ASCII Carriage Return (CR)
  \t  ASCII Horizontal Tab  (TAB)
  \v  ASCII Vertical Tab    (VT)  \x0b
(from the ref. suggested by Fredrik Lund).

To solve the problem you must use "raw strings",
as suggested by the aforementioned expert.

So your filepath ('c:\documents\web\zope\file.ext')
becomes r'c:\documents\web\zope\file.ext' which
protects the '\' by escaping it ('\\').

With such a trick you can obtain the file basename with:
filepath.split('\\')[-1].
Bye.




More information about the Python-list mailing list