On 20 August 2015 at 18:51, Srihari Vijayaraghavan <linux.bug.report...@gmail.com> wrote: > On 20 August 2015 at 18:25, Alan Gauld <alan.ga...@btinternet.com> wrote: >> 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 >> dirs. > > In general I agree, but this is what the os.walk() document states: > "... When topdown is True, the caller can modify the dirnames list > in-place (perhaps using del or slice assignment)..." > > (Yes, the topdown argument of os.walk() is True by default, until > manually modified.) > > Therefore I see no problem with in-place modification of dirnames. > I've made a copy of dirs & iterated over it, which made no difference > in my case. >
Sorry to reply to my own email. I stand corrected. Indeed, while iterating over dirs (in the above example) & doing in-place modification was the source of the problem, giving unpredictable outcome. While iterating over its copy & updating the original dirs, gives expected results. Perhaps my interpretation of the document wasn't correct. Anyway, it's working now. Thank you folks, especially Alan. -- Srihari Vijayaraghavan _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor