-3

I found some example code for ClamAV. And it works fine, but it only scans a single file. Here's the code:

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!"

I'm trying to scan an entire directory, here's my attempt:

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

However, I'm getting the following error:

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

I'm pretty new to Python, and I've read several similar questions and they do something like what I did, I think.

Lennart
  • 21
  • 3
Jack
  • 241
  • 2
  • 14
  • does it help https://stackoverflow.com/questions/34601758/python-ioerror-errno-21-is-a-directory-home-thomasshera-pictures-star-war ? – Vadim May 30 '17 at 06:41
  • 2
    1) If you have working code and need to apply that to multiple objects, at least make it into a function and call that for every object. 2) skip directories returned by `listdir()`, as the error clearly indicates there lies the problem – Anthon May 30 '17 at 06:44
  • Have you read the error? What's unclear about it? – Julien May 30 '17 at 06:50

2 Answers2

3

os.listdir("DIRECTORY") returns list of all files/dir in the DIRECTORY . It is just file names not absolute paths. So, if You are executing this program from a different directory it's bound to fail. If you are sure that everything in the directory is a file, no sub directories. You can try following,

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

Then ,

for file_name in get_abs_names("/home/user/"):
    #Your code goes here.
Ishan Bhatt
  • 9,287
  • 6
  • 23
  • 44
2

The following code will go over all your directory file by file. Your error happens because you try to open a directory as if it is a file instead of entering the dir and opening the files inside

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  
Ishan Bhatt
  • 9,287
  • 6
  • 23
  • 44
Isdj
  • 1,835
  • 1
  • 18
  • 36