for loop specifying the amount of vars

Steve Holden steve at holdenweb.com
Mon Nov 24 15:40:39 EST 2008


Jules Stevenson wrote:
> Hi,
> 
> I have a list which contains a folder structure, for instance:
> 
> dirs=['c:\', 'temp', 'foo', 'bar']
> 
Of course this should really be

  dirs=['c:\\', 'temp', 'foo', 'bar']

but we'll overlook your little syntax error ;-)

> The length of the list can vary. I'd like to be able to construct a
> os.path.join on the list, but as the list can vary in length I'm unsure how
> to do this neatly. I figured I could use a for loop and build the whole
> statement as a string and 'eval it', but I'm aware that this is not a good
> idea. 
> 
> It strikes me that there probably is a very elegant way to achieve what I
> want to do, any pointers much appreciated.
> 
Jules:

Don't reply to someone else's post with a new question, please: many
people use "threaded" readers, and will not even see your subject line.

What you need is

  os.path.join(*dirs)

which tells Python to take the list and turn it into separate arguments.
Fortunately os.path.join will take as many arguments as you care to pass it:

>>> os.path.join(*dirs)
'c:\\temp\\foo\\bar'
>>>

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list