2017-05-30 27 views
-3

我找到了ClamAV的一些示例代碼。它工作正常,但它只掃描一個文件。下面的代碼:打開目錄中的所有文件 - Python

import pyclamav 
import os 

tmpfile = '/home/user/test.txt' 
f = open(tmpfile, 'rb') 

infected, name = pyclamav.scanfile(tmpfile) 
if infected: 
    print "File infected with %s Deleting file." %name 
    os.unlink(file) 
else: 
    print "File is clean!" 

我試圖掃描整個目錄,這裏是我的嘗試:

import pyclamav 
import os 
directory = '/home/user/' 

for filename in os.listdir(directory): 
    f = open(filename, 'rb') 
    infected, name = pyclamav.scanfile(filename) 
    if infected: 
     print "File infected with %s ... Deleting file." %name 
     os.unlink(filename) 
    else: 
     print " %s is clean!" %filename 

不過,我發現了以下錯誤:

Traceback (most recent call last): 
    File "anti.py", line 7, in <module> 
    f = open(filename, 'rb') 
IOError: [Errno 21] Is a directory: 'Public' 

我對Python來說很新鮮,我已經閱讀了幾個類似的問題,他們做了一些類似我所做的事情,我想。

+0

它幫助https://stackoverflow.com/questions/34601758/python-ioerror-errno-21-is-a-directory-home -thomasshera-pictures-star-war? – Paddy

+2

1)如果你有工作代碼,並需要將其應用於多個對象,至少將其作爲一個函數併爲每個對象調用它。 2)跳過'listdir()'返回的目錄,因爲錯誤清楚地表明存在問題 – Anthon

+0

你讀過錯誤嗎?有什麼不清楚的呢? – Julien

回答

2

以下代碼將按文件覆蓋您的所有目錄文件。發生你的錯誤,因爲你試圖打開一個目錄,就好像它是一個文件,而不是進入目錄,打開裏面

for subdir, dirs, files in os.walk(path): # walks through whole directory 
    for file in files: 
     filepath = os.path.join(subdir, file) # path to the file 
     #your code here 
2

os.listdir(「目錄」)的文件返回所有文件的列表/目錄中目錄 。它只是文件名不是絕對路徑。所以,如果你從一個不同的目錄執行這個程序,它肯定會失敗。 如果您確定目錄中的所有內容都是文件,則不需要子目錄。你可以試試以下,

def get_abs_names(path): 
    for file_name in os.listdir(path): 
     yield os.path.join(path, file_name) 

然後,

for file_name in get_abs_names("/home/user/"): 
    #Your code goes here. 
相關問題