Python os.path.join() on a list Ask Question

Python os.path.join() on a list Ask Question

I can do

>>> os.path.join("c:/","home","foo","bar","some.txt")
'c:/home\\foo\\bar\\some.txt'

But, when I do

>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(s)
['c:/', 'home', 'foo', 'bar', 'some.txt']

What am I missing here?

ベストアンサー1

The problem is, os.path.join doesn't take a list as argument, it has to be separate arguments.

To unpack the list into separate arguments required by join (and for the record: list was obtained from a string using split), use * - or the 'splat' operator, thus:

>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'

おすすめ記事