'Converting a path to a file on a network drive from macos to windows
I want to select a file on my Mac, and want the file to be opened on a Windows machine with the path I input on the mac. I have a server the files are located on, maped as follows:
Mac: /Volumes/myraid/projects/file.txt
Windows X:\projects\file.txt
Is there any way I can convert the path from the mac to any file on the server, to be opened on any windows machine, that is able to access the server? The code to manipulate the path should be executed on the windows machine.
Edit: My main problem is the front part of the path, because windows assigns a different letter for each individual drive (e.g. X:\). Especially when I have multiple network drives and I want to be able to select files from all of them.
Solution 1:[1]
I don't know if it's the most elegant solution possible. Neither is this solution safe for the same filename with the same filepath existing on multiple drives, but it works for me.
import os.path
def findnetworkpath(path_input):
path_input = os.path.normpath(path_input) #converts forward slashes to backward slashes
path_snippet = os.path.join(*path_input.split(os.sep)[2:]) #cuts "Volumes/myraid/" out of the path
dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)] #checks for existing drives
for drive in drives:
if os.path.exists(drive + "\\" + path_snippet): #checks if the path snippet is the subpath of any connected drives
return drive + "\\" + path_snippet #function returns the path the windows machine has to the file
print(findnetworkpath("Volumes/myraid/projects/file.txt"))
Solution 2:[2]
You can use os.path.join(), which joins a list of directories according to the rules of the platform it's run on.
>>> # windows
>>> os.path.join('projects', 'file.txt')
projects\file.txt
>>> # mac osx
>>> os.path.join('projects', 'file.txt')
projects/file.txt
You can also use os.name to get the operating system the program is currently on so you can edit the start of your path accordingly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David.Le |
| Solution 2 |
