我正在使用python进行跨平台路径交换。
import platform
def filenameFix(filename):
if platform.system() in ("Windows", "Microsoft"):
return filename.replace ( "/Volumes/projects/", "p:/")
else:
return filename.replace( "p:/", "/Volumes/projects/" )
return filename
这适用于交换/Volumes/projects/
的路径,但我希望它也在第一个if块中交换Volumes/projects
的路径。唯一的区别是在删除Volumes
之前的正斜杠...我怎么能这样做?
答案 0 :(得分:2)
Windows支持路径中的正斜杠,linux也是如此。因此,您可以在所有位置使用/
,这也有助于消除使用\
字符转义的问题。
如果这对您不起作用,或者您也在其他系统上运行,或者系统运行方式不同(例如mac)。然后,您可以使用os.path.join()
或者你可以使用它:
import sys
def get_path(filename):
if sys.platform == 'win32':
return filename.replace("/Volumes/projects/", "p:/")
else:
return filename.replace("p:/", "/Volumes/projects/")
最佳做法是不对路径的“root”元素进行硬编码,而是通过使用os.getenv('HOME')
或某些此类常量或通过获取正在运行的脚本的相对路径来相对获取它,以及使用以下方法构建目录树:
this_dir = os.path.dirname(os.path.abspath(__file__))
答案 1 :(得分:1)
Python比你想象的要好得多,如果你只是让它:)
import os.path
def get_dir():
return "p:/" if platform.system() in ("Windows", "Microsoft") else "..."
def full_filename(filename):
return os.path.join(get_dir(), filename)
答案 2 :(得分:0)
您可以在没有前导/
的情况下进行替换,然后删除可能存在的任何前导/
。
import platform
def filenameFix(filename):
if platform.system() in ("Windows", "Microsoft"):
return filename.replace( "Volumes/projects/", "p:/").lstrip('/')
else:
return filename.replace( "p:/", "/Volumes/projects/" )
return filename
>>> s1
'/Volumes/projects/blah/'
>>> s2
'Volumes/projects/blah/'
>>> s1.replace('Volumes/projects/', 'p:/').lstrip('/')
'p:/blah/'
>>> s2.replace('Volumes/projects/', 'p:/').lstrip('/')
'p:/blah/'
答案 3 :(得分:0)
我想知道这实际上是否比我最初的答案更能回答你的问题...如果第一次替换失败,请寻找相同的模式但没有斜线。
def filenameFix(filename):
if platform.system() in ("Windows", "Microsoft"):
return filename.replace ( "/Volumes/projects/", "p:/").replace("Volumes/projects/", "p:/")
else:
return filename.replace( "p:/", "/Volumes/projects/" )
return filename