将路径转换为网络驱动器上的文件从macos到windows

问题描述 投票:0回答:2

我想在Mac上选择一个文件,并希望在Windows机器上打开文件,并在mac上输入路径。我有一个文件所在的服务器,maped如下:

Mac:/Volumes/myraid/projects/file.txt

Windows X:\projects\file.txt

有没有什么办法可以将路径从mac转换为服务器上的任何文件,在任何可以访问服务器的Windows机器上打开?操作路径的代码应该在windows机器上执行。

编辑:我的主要问题是路径的前部,因为窗口为每个驱动器分配不同的字母(例如X:\)。特别是当我有多个网络驱动器,我希望能够从所有这些驱动器中选择文件。

python windows macos path network-drive
2个回答
1
投票

我不知道这是否是最优雅的解决方案。对于具有多个驱动器上存在的相同文件路径的相同文件名,此解决方案也不安全,但它适用于我。

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"))

0
投票

您可以使用os.path.join(),它根据运行的平台规则连接目录列表。

>>> # windows
>>> os.path.join('projects', 'file.txt')
projects\file.txt
>>> # mac osx
>>> os.path.join('projects', 'file.txt')
projects/file.txt

您还可以使用os.name获取程序当前所在的操作系统,以便相应地编辑路径的起点。

© www.soinside.com 2019 - 2024. All rights reserved.