tags:

views:

1050

answers:

3

In Unix all disks are exposed as paths in the main filesystem, so os.walk('/') would traverse, for example, /media/cdrom as well as the primary hard disk, and that is undesirable for some applications.

How do I get an os.walk that stays on a single device?

Related:

+1  A: 

os.walk() can't tell (as far as I know) that it is browsing a different drive. You will need to check that yourself.

Try using os.stat(), or checking that the root variable from os.walk() is not /media

jcoon
+9  A: 

From os.walk docs:

When topdown is true, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search

So something like this should work:

for root, dirnames, filenames in os.walk(...):
  dirnames[:] = [
    dir for dir in dirnames
    if not os.path.ismount(os.path.join(root, dir))]
  ...
Constantin
a brilliantly concise answer.
Matt Joiner
+1  A: 

I think os.path.ismount might work for you. You code might look something like this:

import os
import os.path
for root, dirs, files in os.walk('/'):
    # Handle files.
    dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), 
                  dirs)

You may also find this answer helpful in building your solution.

*Thanks for the comments on filtering dirs correctly.

zweiterlinde
Reassigning dirs will certainly not work.
Constantin
You can fix is by chinging your code to "dirs[:] = filter(...)" instead, mutating the list in-place rather than reassiging
Brian