Skip to content
Advertisement

Python: Get Mount Point on Windows or Linux

I need a function to determine if a directory is a mount point for a drive. I found this code already which works well for linux:

def getmount(path):
  path = os.path.abspath(path)
  while path != os.path.sep:
    if os.path.ismount(path):
      return path
    path = os.path.abspath(os.path.join(path, os.pardir))
  return path

But I’m not sure how I would get this to work on windows. Can I just assume the mount point is the drive letter (e.g. C:)? I believe it is possible to have a network mount on windows so I’d like to be able to detect that mount as well.

Advertisement

Answer

Windows didn’t use to call them “mount points” [edit: it now does, see below!], and the two typical/traditional syntaxes you can find for them are either a drive letter, e.g. Z:, or else \hostname (with two leading backslashes: escape carefully or use r'...' notation in Python fpr such literal strings).

edit: since NTFS 5.0 mount points are supported, but according to this post the API for them is in quite a state — “broken and ill-documented”, the post’s title says. Maybe executing the microsoft-supplied mountvol.exe is the least painful way — mountvol drive:path /L should emit the mounted volume name for the specified path, or just mountvol such list all such mounts (I have to say “should” because I can’t check right now). You can execute it with subprocess.Popen and check its output.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement