pythonmacosterminalusbdirectory-listing

Obtain path of USB Stick with Terminal on macOS with Python3


I‘d like to write a Python program which first detects a new USB disk with Terminal on macOS, then returns me the full path to the stick.

I‘ve tried to implement it like that:

os.chdir(‘/Volumes‘)
#then do some listing
List = os.listdir()

But this returns me just

My_USB_Stick
Macintosh HD

I have no idea how to get the path of the connected drive, which excludes Macintosh HD…

Any Ideas ? Looking forward to hearing from you ;)

My_USB


Solution

  • One way to to it would be:

    1. Find a way to list the complete path of all files while performing the ls command in python
    2. Loop through the list and exclude the Macintosh HD file.

    There is another easier way to implement the same. You could loop over the List and add the current path (/Volumes/) to the files/folders in the list. Here is an implementation of the same:

    import os
    os.chdir('/Volumes')
    # then do some listing
    List = os.listdir()
    i = 0
    while i < len(List):
        if (List[i] == 'Macintosh HD'):
            del List[i:i+1]
            continue
        else:
            List[i] = '/Volumes/' + List[i]
            i += 1
    print(List)