[Tutor] useful function or reinventing the wheel??

Dave Angel d at davea.name
Tue Nov 29 06:12:21 CET 2011


On 11/28/2011 11:30 PM, Mark Lybrand wrote:
> I am a habitual wheel re-inventor, so it would not surprise me, but I made
> this little function that I was kinda proud of (seeing that I have only
> been learning python like a week now):
>
> It just takes a directory and checks to see if all the directories,
> sub-directories exist and creates them if they don't:
>
> def insure_exists_dir(dir):
>    grow_path = [dir]
>    while not os.path.ismount(grow_path[0]):
>      part_tuple = os.path.split(grow_path[0])
>      grow_path.insert(0, part_tuple[0])
>
>    del(grow_path[0])
>    while grow_path:
>      if not os.path.exists(grow_path[0]):
>        os.mkdir(grow_path[0])
>      del(grow_path[0])
>    return(dir)
>
>
> Opinions?  What should I really be using?
>
I couldn't follow your code, but finally concluded that it's trying to 
create a directory, creating the directories parents also if they don't 
exist either.  It would be much simpler if written recursively, but 
there's no need.

Check out os.makedirs(), and see if it meets your needs.   (that's 
makedirs() function, in the os module)



-- 

DaveA



More information about the Tutor mailing list