【问题标题】:Python file names as dictionary keysPython 文件名作为字典键
【发布时间】:2013-05-01 13:46:51
【问题描述】:

我想在解析驱动器或文件夹时创建一个字典“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)

【问题讨论】:

  • 感谢您发布错误,但如果您附上完整代码会很好
  • 字符串是合法的字典键,无论它是否包含破折号。问题可能出在其他地方。字典的值看起来像一个整数。
  • 问题似乎是您正在为键控文件名存储一个int 对象,而不是您编写的具有addScore 方法的任何Class 的实例。跨度>

标签: python dictionary key filenames


【解决方案1】:

正如您在此处看到的,问题就像 @pztrick 在 cmets 中向您提出的问题。

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

【讨论】:

  • 啊——该死的。我错过了部分代码中的“.addScore”函数,并删除了直接设置分数的代码行,因为我在以前的版本中使用它。你的提示是对的。谢谢。
猜你喜欢
  • 2022-01-11
  • 2013-08-23
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
相关资源
最近更新 更多