0

我想在解析驱动器或文件夹时创建一个字典“file_stats”,其中包含具有文件统计信息的对象。
我使用路径+文件名组合作为这个字典
的键对象有一个名为“addScore”的方法。
我的问题是文件名有时包含导致这些错误的“-”等字符:

Error: Yara Rule Check error while checking FILE: C:\file\file-name Traceback (most recent call last):
File "scan.py", line 327, in process_file
addScore(filePath)
File "scan.py", line 393, in addScore
file_stats[filePath].addScore(score)
AttributeError: 'int' object has no attribute 'addScore'

我使用文件名作为字典的键来快速检查文件是否已经在字典中。

我应该摒弃使用文件路径作为字典键的想法,还是有一种简单的方法来转义字符串?

file_stats = {}
for root, directories, files in os.walk (drive, onerror=walkError, followlinks=False):
    filePath = os.path.join(root,filename)
    if not filePath in file_stats:
        file_stats[filePath] = FileStats()
        file_stats[filePath].addScore(score)
4

1 回答 1

1

正如您在此处看到的,问题就像@pztrick 在对您的问题的评论中指出的那样。

>>> class StatsObject(object):
...     def addScore(self, score):
...         print score
...
>>> file_stats = {"/path/to-something/hyphenated": StatsObject()}
>>> file_stats["/path/to-something/hyphenated"].addScore(10)
>>> file_stats["/another/hyphenated-path"] = 10
10
>>> file_stats["/another/hyphenated-path"].addScore(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'addScore'

这个最小的例子对你有用吗(可能有不同的起始路径)

import os

class FileStats(object):
    def addScore(self, score):
        print score

score = 10
file_stats = {}
for root, directories, files in os.walk ("/tmp", followlinks=False):
    for filename in files:
        filePath = os.path.join(root,filename)
        if not filePath in file_stats:
            file_stats[filePath] = FileStats()
            file_stats[filePath].addScore(score)
于 2013-05-07T14:53:04.210 回答