[Tutor] Request for help with os.walk() combining os.path.ismount() in Linux

Alan Gauld alan.gauld at btinternet.com
Thu Aug 20 10:25:29 CEST 2015

On 20/08/15 04:03, Srihari Vijayaraghavan wrote:

> out = sys.stdout.write
> for root, dirs, files in os.walk("/"):
>     out("The dirs before removing mount points: %s\n" % dirs)
>     for d in dirs:
>         dname = os.path.join(root, d)
>         if os.path.ismount(dname):
>             dirs.remove(d)

It's never a good idea to remove items from the thing
you are iterating over. Create a copy of dirs (dirs[:])
to iterate on then remove the items from the original

It always amazes me how often the same issues come up in
rapid succession. We must have had 4 or 5 of these types
of errors in the last couple of months, and other times
we go for 6 months or more without it being raised! :-)

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list