Reputation: 19379
If there a pre-defined single-line easy to remember python command that extracts a drive letter from a string filepath useful on both mac and windows?
if MAC:
filepathString = '/Volumes/Some Documents/The Doc.txt'
would result to :
myDrive = '/Volumes/transfer'
if WIN:
filepathString = 'c:\Some Documents\The Doc.txt'
would result to :
myDrive = 'c:'
Upvotes: 1
Views: 4604
Reputation: 3756
Pathlib now has a property drive
which makes this really easy by calling path.drive
from pathlib import Path
path = Path(r'F:\\test\folder\file.txt')
path.drive
Upvotes: 6
Reputation: 141
Simple example(Windows):
import os
import pathlib
drive = pathlib.Path(os.getcwd()).parts[0]
Upvotes: 3
Reputation: 1704
I think you're going to have to write custom code for this. Use platform.system()
or platform.uname()
to find out what kind of system you're on, then use os.path
functions to extract the drive/volume name in a way appropriate to the detected platform.
A sketch:
def volume_name(path):
if platform.system() == "Darwin":
return re.search("^\/Volumes\/[^/]+/", path).group(0)
elif platform.system() == "Windows":
return path[0:2]
Upvotes: 2
Reputation: 10193
Try the splitdrive
method from the os.path
module along with the regular split
. It's not single line, but then again I can't see how the code would know to append transfer
to the volume path, or detect if a given path is from Windows or Unix (remember C:
is a valid Unix filename).
Upvotes: 4