Convert mac path to posix in python

I am stuck trying to convert a Mac path to a POSIX path in Python. I want to convert something like this:

'Main HD:Users:sasha:Documents:SomeText.txt' 

:

 '/Users/sasha/Documents/SomeText.txt' 

I know that I could just split the string into a list and then reconnect with the correct delimiter. But I believe that there should be a much more elegant solution that I am missing, perhaps using the python modules "macpath" or "os.path". However, I was not able to define a function inside these modules that would do the conversion trick of the two formats.

Another problem with a simple string manipulation solution is that if I have multiple HDs, then a simple solution will not work. For instance:

If you have a path, for example:

 'Extra HD:SomeFolder:SomeOtherText.txt' 

we would like this transformation to be:

 '/Volumes/Extra HD/SomeFolder/SomeOtherText.txt' 

Not for:

 '/SomeFolder/SomeOtherText.txt' 
+5
source share
2 answers

To do this, you can use the Pythons subprocess module:

 #!/usr/bin/python import subprocess def asExec(ascript): osa = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) return osa.communicate(ascript)[0] def asConv(astr): astr = astr.replace('"', '" & quote & "') return '"{}"'.format(astr) def aScript(aspath): ascript = ''' set posixPath to POSIX path of {0} '''.format(asConv(aspath)) return ascript aliasPath = "Main HD:Users:sasha:Documents:SomeText.txt" print(asExec(aScript(aliasPath))) 

Result:

/ Main HD / Users / sasha / Documents / SomeText.txt

+2
source

There are no methods in the standard library. os.path provides thread manipulation methods for current os, and there are no methods for converting path styles or change delimiters. Specific os manipulation modules, such as macpath , posixpath and ntpath , do not contain methods for converting path separator characters, etc. (Source: os.path docs )

As such, I think replacing the delimiter with string manipulations is a reasonable solution to this problem.

+1
source

All Articles