how to call os.path.join() on a list ...

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Feb 26 23:41:53 EST 2007


"funkyj" <funkyj at gmail.com> writes:

> I want to call os.path.join() on a list instead of a variable list of
> arguments.  I.e.
>
>     [...]
>     >>> import os
>     >>> import string
>     >>> p = os.environ['PWD']
>     >>> p
>     '/tmp/a/b/c/d'
>     >>> os.path.join(string.split(p, os.sep))
>     ['', 'tmp', 'a', 'b', 'c', 'd']
>     >>>
>
> the value returned by os.path.join() is obviously not the desired
> result ...

Nor is the value returned by the string 'split' function quite what
you describe.

    >>> p.split(os.sep)
    ['', 'tmp', 'a', 'b', 'c', 'd']
    >>> os.path.split(p)
    ('/tmp/a/b/c', 'd')

> [...]
> What is the python idiom for callling a function like os.path.join()
> that takes a variable number of arguments when you currently have
> the arguements in a list variable?

    >>> import os
    >>> p = ["/tmp", "a", "b", "c", "d"]
    >>> os.path.join(*p)
    '/tmp/a/b/c/d'

"funkyj" <funkyj at gmail.com> writes:

> I can just do:
>
>     os.sep.join(string.split(p, os.sep))
>
> it isn't "funcall" but it gets me where I want to go.

It also isn't 'os.path.join'.

    >>> p = ["/tmp", "a", "b/", "c/", "d"]
    >>> os.sep.join(p)
    '/tmp/a/b//c//d'
    >>> os.path.join(*p)
    '/tmp/a/b/c/d'

-- 
 \       "Never use a long word when there's a commensurate diminutive |
  `\                                 available."  -- Stan Kelly-Bootle |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list