Stripping parts of a path

Tim Roberts timr at probo.com
Sun Jul 27 00:32:59 EDT 2008


Tim Cook <timothywayne.cook at gmail.com> wrote:
>
>I just ran into an issue with the rstrip method when using it on path
>strings.
>
>When executing a function I have a need to strip off a portion of the
>current working directory and add on a path to a log file.  Initially
>this worked great but then I added a branch in SVN which caused the path
>to contain 'LNCCWorkshop'.  The rstrip() then began removing the
>characters 'shop' leaving an incorrect path to the log file.  When I
>hard coded this path it worked okay but then did the same thing later in
>the file when I needed to point to a database. The code worked fine with
>a different path.  Here are some code fragments. 
> 
>logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log'

This doesn't do what you think it does.  The parameter to rstrip is a set:
as long as the last character is in the set 'abcdhiloprs/', it will remove
it and check the next one.  All of the characters in "shop" are in that
set.

In a few minutes, I couldn't think of a clever one-liner to do this.  You
could do it with re.sub, but that seems like overkill.

  chk = '/src/oship/atbldr'
  cwd = os.getcwd()
  if cwd.endswith( chk ):
    cwd = cwd[:-len(chk)]
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list