Detect whether file is on a network drive in python

3k views Asked by At

How can I determine if a file is on a network drive or not? I want to include situations where the path looks like it's on local disk, but one of the directories in the path is in fact a symbolic link to a network drive.

1

There are 1 answers

0
oathead On BEST ANSWER

I'm going to assume you can get a list of network filesystems and their base mount points, which you could get from parsing mount or df. If that's the case you should be able to do everything you want to do with a few different functions from os.path

This will take a filename and a path that's a network filesystem. The path.realpath will convert symlinks to absolute path of the file they're linked to.

def is_netfile(fname, netfs):
    fname = path.realpath(fname)
    netfs = path.realpath(netfs)
    if path.commonprefix([ netfs, fname ]) == netfs:
        return True
    else:
        return False

You could take his an use it along with os.walk to move through the directory structure and capture all the files that are or link to files on a specific network fileshare

start_dir = '/some/starting/dir'
net1 = '/some/network/filesystem'
remote_files = []

for root, dirs, files in os.walk(start_dir):
    for f in files:
        if is_netfile( path.join(root,f), net1):
            remote_files.append( path.join(root,f))

print remote_files