簡體   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