2013-05-07 202 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