2013-05-07 199 views
0

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

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) 
+1

感谢您发布的错误,但如果你与你的全码 – 2013-05-07 14:42:19

+1

一个伴随着它,它会是不错字符串是一个合法的字典密钥,不管它是否包含破折号。问题可能在其他地方。你的字典的值看起来像一个整数。 – eumiro 2013-05-07 14:43:34

+3

这个问题似乎是你为键控文件名存储一个int对象,而不是你编写的具有addScore方法的任何'Class'实例。 – pztrick 2013-05-07 14:44:50

回答

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) 
+0

啊 - 该死的。我错过了部分代码中的“.addScore”函数,并删除了直接设置分数的代码行,就像我在之前的版本中使用它一样。你的提示是正确的。谢谢。 – JohnGalt 2013-05-07 14:59:42