简体   繁体   中英

Python: How to extract Drive from Filepath string

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:'

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).

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]

Simple example(Windows):

import os
import pathlib
drive = pathlib.Path(os.getcwd()).parts[0]

Pathlib now has a property drive which makes this really easy by calling path.drive

Full Example:
from pathlib import Path
path = Path(r'F:\\test\folder\file.txt')
path.drive

PathLib Documentation link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM