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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With