好吧,我完全困惑了。我整晚都在做这个,但我不能让它工作。我有权查看文件,我只想读那该死的东西。每次我尝试我得到:
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'
这是我的代码。它还没有完成,但我觉得我至少应该为我正在测试的部分获得正确的值。基本上,我想查看一个文件夹,如果有一个文件扫描它寻找我设置的签名。如果有文件夹,我将或不扫描它们,这取决于指定的深度
。如果有深度
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()
我冒昧地猜测test\test
是一个目录,出现了一些异常。您盲目地捕获异常并尝试将目录作为文件打开。这在Windows上给出了错误13。
使用os。路径isdir
来区分文件和目录,而不是尝试。。。除了
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