如何使用 Python 知道 COMPUTER (windows 7) 的内容?

How to know the contents of COMPUTER (windows 7) using Python?

我想找到一个更简单的版本来检查是否插入了任何 USB 设备,所以我尝试遍历 COMPUTER 的内容。但是我找不到 [My] Computer 的路径,所以我尝试了以下方法:

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

但是程序报错:

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\*.*'

谁能告诉我如何解决这个问题?

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

我的程序使用 try 语句,这意味着它将执行 os.listdir(),如果它 return 是我在 except 子句中指定的两个错误之一,它会将导致该错误的驱动器号附加到列表中,然后 return 列表。我没有对其进行太多测试,因此如果您在测试期间收到任何其他错误,您可能需要将它们添加到 except 中。可能有更有效的方法来做到这一点,但它有效,对吧?对我来说足够好了。

import string
import os

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