Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert mac path to posix in python

Tags:

python

path

macos

I'm 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'

to this:

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

I know I could simply split the string into a list and then rejoin it with the correct separator. But I believe there must be a much more elegant solution I'm missing, possibly involving the "macpath" or "os.path" python modules. However, I've not been able to figure out a function within these modules that will do the trick of converting between the two formats.

An additional problem of the simple string manipulation solution is that if I have multiple HDs, then a simple solution won't work. For instance:

If you have a path like:

'Extra HD:SomeFolder:SomeOtherText.txt'

we would want that to be converted to:

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

Not to:

'/SomeFolder/SomeOtherText.txt'
like image 488
alexvicegrab Avatar asked Oct 19 '22 11:10

alexvicegrab


1 Answers

You could use Pythons subprocess module for this:

#!/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

like image 161
l'L'l Avatar answered Oct 22 '22 00:10

l'L'l