-1

I wanted to find out a simpler version to check if there is any USB device plugged in so I tried to iterate over the contents of COMPUTER. However i could not find the path for [My] Computer, so i just tried out the following:

import os
contents = os.listdir("Computer")

But the program threw an error:

Traceback (most recent call last):
File "C:/Python33/usb.py", line 3, in <module>
folder = os.listdir("Computer")
FileNotFoundError: [WinError 3] The system cannot find the path specified: 
'Computer\\*.*'

Can anyone tell me how can i resolve this problem?

AkaiShuichi
  • 144
  • 1
  • 1
  • 9

2 Answers2

0
import os
import string

letters = list(string.ascii_lowercase) #Just a list of all the lowercase letters

def list_subtract(list1, list2): #Function to return all entries in list1 subtracted by the entries in list2
        list_difference = []
        for x in list1:
                if x not in list2:
                        list_difference.append(x)
        return list_difference

def devices():
        not_drives = []
        for x in letters:
                try:
                        drive = os.listdir('%(test_drive)s:' % {'test_drive' : x}) #It tries os.listdir() for all 26 drive letters
                except (FileNotFoundError, PermissionError): #If it recieves a FileNotFoundError (Drive doesn't exist) or a PermissionError (Drive is busy)
                        not_drives.append(x) #Puts that drive letter in a list of all drive letters that don't correspond to a drive
        return list_subtract(letters, not_drives) #returns all letters - letters that aren't drives

print(devices())

My program uses the try statement, meaning it will execute the os.listdir(), and if it returns one of thee two errors I specified in the except clause, it will append the drive letter that caused that error to a list, then return the list. I didn't test it much, so if there are any other errors that you receive during testing, you may want to add those to the except. There is probably a more efficient way to do this, but it works, right? Good enough for me.

Bretsky
  • 423
  • 8
  • 23
0
import string
import os

drive_letters = []
allchars = string.ascii_lowercase
for x in allchars:
    if os.path.exists(x + ":"):
        drive_letters.append(x)
AkaiShuichi
  • 144
  • 1
  • 1
  • 9