2012-11-06 122 views
0

好的,我完全不知所措。我一整晚都在努力工作,但卻無法完成工作。我有權讓我看看這個文件,我想要做的就是閱讀這個文件。每次我嘗試我得到:Python IO錯誤:Errno 13權限被拒絕

Traceback (most recent call last): 
    File "<pyshell#3>", line 1, in <module> 
    scan('test', rules, 0) 
    File "C:\Python32\PythonStuff\csc242hw7\csc242hw7.py", line 45, in scan 
    files = open(n, 'r') 
IOError: [Errno 13] Permission denied: 'test\\test' 

這是我的代碼。這是未完成的,但我覺得我應該至少爲我正在測試的部分獲得正確的值。基本上我想看看一個文件夾,如果有文件掃描它尋找任何我設置我的signatures。如果有文件夾,我將或不會掃描它們,具體取決於指定的depth。如果有depth < 0那麼它會返回。如果depth == 0那麼它只會掃描第一個文件夾中的元素。如果depth > 0它將掃描文件夾直到指定的深度。所有這些都沒有想到,因爲無論什麼原因,我沒有權限閱讀文件。我不知道我做錯了什麼。

def scan(pathname, signatures, depth): 
'''Recusively scans all the files contained in the folder pathname up 
until the specificed depth''' 
    # Reconstruct this! 
    if depth < 0: 
     return 
    elif depth == 0: 
     for item in os.listdir(pathname): 
      n = os.path.join(pathname, item) 
      try: 
       # List a directory on n 
       scan(n, signatures, depth) 
      except: 
       # Do what you should for a file 
       files = open(n, 'r') 
       text = file.read() 
       for virus in signatures: 
        if text.find(signatures[virus]) > 0: 
         print('{}, found virus {}'.format(n, virus)) 
       files.close() 

只是一個快速編輯:

下面這段代碼確實非常類似的東西,但我無法控制的深度。但是,它工作正常。

def oldscan(pathname, signatures): 
    '''recursively scans all files contained, directly or 
     indirectly, in the folder pathname''' 
    for item in os.listdir(pathname): 
     n = os.path.join(pathname, item) 
     try: 
      oldscan(n, signatures) 
     except: 
      f = open(n, 'r') 
      s = f.read() 
      for virus in signatures: 
       if s.find(signatures[virus]) > 0: 
        print('{}, found virus {}'.format(n,virus)) 
      f.close() 
+0

該文件的權限究竟是什麼?您是否使用與您用來嘗試打開文件的用戶名相同的用戶名來運行Python程序? –

+0

只需執行'ls -l'並把輸出放在這裏 –

+0

我不確定我是否理解。我是我的電腦的唯一用戶,因此具有管理功能。我很困惑,因爲我確實有類似的代碼可以很好地工作。 –

回答

1

我冒昧猜測test\test是一個目錄,並且發生了一些異常。您會盲目地捕獲異常並嘗試將該目錄作爲文件打開。這給了Windows上的Errno 13。使用os.path.isdir來區分文件和目錄,而不是try ... except。

for item in os.listdir(pathname): 
     n = os.path.join(pathname, item) 
     if os.path.isdir(n): 
      # List a directory on n 
      scan(n, signatures, depth) 
     else: 
      # Do what you should for a file 
+0

'test'是與我的.py文件位於同一文件夾中的文件夾的名稱,上面的代碼正在嘗試執行。 –

+0

@DanielLoveJr無論如何我建議擺脫try/except;它可能隱藏了原始錯誤。 –

+0

那麼我會檢查是否呃... os.path.isdir(n)== True?如果這是真的,那麼這是其中的一個文件夾?如果它是假的,那麼它是一個文件,我讀它? –

相關問題