Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?

Tags:

python

unix

I'm writing a python script that uses os.walk() to walk a directory tree. I'd like to give it the ability to skip subdirectories that are mounted to a different file system, the way find -xdev does. Checking through the documentation on os.walk(), I didn't see any argument to pass in for it to do that automatically. Is there something I can use to do the filtering myself? Hopefully something that runs on both Linux and Mac OS X?

like image 406
Micah Avatar asked Mar 02 '23 00:03

Micah


2 Answers

os.path.ismount()

like image 94
anthony Avatar answered Apr 26 '23 09:04

anthony


I think you can use a combination of the os.stat call and a filtering of the dirnames given by os.walk to do what you want. Something like this:

import os
for root, dirs, files in os.walk(somerootdir) :
    do_processing(root, dirs, files)
    dirs = [i for i in dirs if os.stat(os.path.join(root, i)).st_dev == os.stat(root).st_dev]

That should modify the list of directories to recurse into, by removing those which do not have the same device.

I have no idea on how it will work on OS X, but it seems to be working here in Linux, after a very little bit of testing.

like image 24
sykora Avatar answered Apr 26 '23 10:04

sykora