好的,我完全不知所措。我一直在努力工作,我无法让它工作。我已经预先查看了该文件,我想要做的就是阅读这个糟糕的事情。我每次尝试都会得到:
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 :(得分:1)
我冒昧地猜测test\test
是一个目录,并且发生了一些异常。您盲目地捕获异常并尝试将该目录作为文件打开。这给了Errno 13在Windows上。
使用os.path.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