Search code examples
pythonpython-3.xnetwork-programming

Access network shares from Windows, Mac and Linux


I need to read files from a network share using Python. The Python programm needs to work on macOS, Windows (the systems we use across our team in development) and Linux (which the server is running).

In macOS I can read from the mounted network share like this:

file_path = '//Volumes/data/path/to/files'
list_of_files = os.listdir(file_path)

In Windows I can do

file_path = 'V:\path\to\files'
list_of_files = os.listdir(file_path)

or alternatively

file_path = '//our.server.de/share/data/path/to/files'
list_of_files = os.listdir(file_path)

I'm sure there is something similar in Linux (which I haven't tried yet).

I suppose I could somehow determine the current OS and use if-statements, but I was hoping there is a better way to achieve this.

I was hoping I could get the files somehow over the network instead of over the local file system (if that makes sense).

Any hints are greatly appreciated!


Solution

  • Based on the comment by @Some programmer dude above I think this may be the solution:

    import os
    import platform
    
    def set_path_root():
        if platform.system() == 'Darwin':
            os.system("osascript -e 'mount volume \"smb://our.server.de/share/data\"'") 
            path_root = '//Volumes/data'
        
        elif platform.system() == 'Windows':
            path_root = '//our.server.de/share/data'
    
        elif platform.system() == 'Linux':
            path_root = '/whatever/works/on/Linux'
    
      return path_root
    
    path_root = set_path_root()
    
    file_path = f'{path_root}/path/to/files'
    
    list_of_files = os.listdir(file_path)
    

    For the values of platform.system() see this question. For the mounting of the volume in macOS see this question