2015-03-31 73 views
-1

我想找出一個更簡單的版本來檢查是否有任何USB設備插入,所以我試圖迭代計算機的內容。但是我無法找到[我的計算機的路徑,所以我只是嘗試了以下內容:如何使用Python知道計算機(Windows 7)的內容?

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

誰能告訴我,我怎樣才能解決這個問題?

+1

「Computer」是一個文件夾名? – Marcin 2015-03-31 05:55:54

+0

它相當於我的電腦在Windows 7 – pyUser 2015-03-31 05:56:44

+0

您可能想看看這篇文章:http://stackoverflow.com/questions/8110310/simple-way-to-query-connected-usb-devices-info- in-python – AChampion 2015-03-31 05:57:01

回答

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

我的程序使用try聲明,這意味着它將執行os.listdir(),如果返回你的一個我在規定者除外條款兩個錯誤,它會追加造成的驅動器盤符錯誤列表,然後返回列表。我沒有對它進行太多的測試,所以如果在測試過程中收到任何其他錯誤,您可能需要將這些錯誤添加到除外。這可能是一種更有效的方式,但它有效,對嗎?對我來說足夠了。

0
import string 
import os 

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