繁体   English   中英

Python文件名作为字典键

[英]Python file names as dictionary keys

我想在解析驱动器或文件夹时创建一个包含文件统计信息对象的字典“ file_stats”。
我使用path + filename组合作为此字典的键
这些对象具有一种称为“ 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)

正如您在此处看到的那样,问题就像@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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM