好吧,我完全困惑了。我整晚都在研究这个问题,但无法让它发挥作用。我有权查看该文件,我想做的就是阅读该死的东西。每次我尝试都会得到:
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()