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

Srihari Vijayaraghavan linux.bug.reporting at gmail.com
Thu Aug 20 11:16:51 CEST 2015

On 20 August 2015 at 18:51, Srihari Vijayaraghavan
<linux.bug.reporting at gmail.com> wrote:
> On 20 August 2015 at 18:25, Alan Gauld <alan.gauld at 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

More information about the Tutor mailing list