我找到了一些ClamAV的示例代码。它工作正常,但它只扫描一个文件。这是代码:
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 :(得分: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
答案 1 :(得分:2)
os.listdir(&#34; DIRECTORY&#34;)返回DIRECTORY中所有文件/目录的列表。它只是文件名而不是绝对路径。因此,如果您从不同的目录执行此程序,它必然会失败。 如果您确定目录中的所有内容都是文件,则没有子目录。您可以尝试以下,
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.