Python IOError:Errno 13权限被拒绝

2024-04-29 18:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我完全困惑了。我整晚都在做这件事,我没法让它起作用。我有预感要查档案,我只想看看那该死的东西。每次我试着得到:

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()

Tags: theintest文件夹forscanifos
1条回答
网友
1楼 · 发布于 2024-04-29 18:27:24

我冒昧地猜测test\test是一个目录,并且发生了一些异常。您盲目地捕获异常并尝试将目录作为文件打开。窗户上有13号错误。

使用os.path.isdir来区分文件和目录,而不是try…except。

    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

相关问题 更多 >