os.path.isdir question

MRAB google at mrabarnett.plus.com
Sun Mar 16 15:27:30 EDT 2008


On Mar 16, 2:27 am, Benjamin <musiccomposit... at gmail.com> wrote:
> On Mar 15, 8:12 pm, lampshade <mwolff... at gmail.com> wrote:> Hello,
>
> > I'm having some problems with  os.path.isdir  I think it is something
> > simple that I'm overlooking.
>
> > #!/usr/bin/python
> > import os
>
> > my_path = os.path.expanduser("~/pictures/")
> > print my_path
> > results = os.listdir(my_path)
> > for a_result in results:
> >     if os.path.isdir(str(my_path) + str(a_result)):
>
> Try if os.path.isdir(os.path.join(my_path, a_result)):>         results.remove(a_result)
>
> > for x in results: print x
>
> > The problem is, that the directories are never removed.  Can anyone
> > point out what I'm missing that is causing the bug?  Is there a better
> > way of doing this?
>
> You should always use os.path.join to join paths. You shouldn't add
> them like normal strings. I suspect you're getting a combination which
> doesn't exist, so it isn't a dir. :)
>
You are also removing items from 'results' while iterating over it,
which has an undefined behaviour. It would be better to build a new
list of those that aren't directories.



More information about the Python-list mailing list