根据文件扩展名自动选择文件处理程序

2024-06-28 14:53:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是这样看的:

class BaseHandler:
    def open(self): pass
    def close(self): pass

class TXTHandler(BaseHandler):
    def open(self): pass
    def close(self): pass

class XMLHandler(BaseHandler):
    def open(self): pass
    def close(self): pass

def open_file(file_path):
    handler = BaseHandler(file_path)

例如,如果文件路径为“\文件.xml'它必须返回XMLHandler。 谁能告诉我,我需要做什么来实现这个功能?你知道吗

我知道我可以通过if-elif-else语句来实现这一点,但我正在努力避免一打elif。你知道吗


Tags: 文件pathself路径closedefpassopen
2条回答

您可以根据文件类型,例如通过检查扩展名:Checking file extension 选择适当的处理程序类。你知道吗

沿着这些思路:

def open_file(file_path):
    if file_path.lower().endswith('.txt'):
        handler = TxtHandler(file_path)
    elif file_path.lower().endswith('.xml'):
        handler = XMLHandler(file_path)
    else:
        handler = BaseHandler(file_path) #or error

这是我喜欢的Python方式:

import os
handlers = {'.xml': XMLHandler, '.txt': TxtHandler}

def open_file(file_path):
    ext = os.path.splitext(file_path)[1]
    handler = handlers.get(ext, BaseHandler)

在上面的代码中,我使用字典将处理程序与扩展关联起来。你知道吗

open_file函数中,我提取扩展名并使用它从字典中获取处理程序,同时考虑键不存在的情况。你知道吗

我也可以这样做:

if ext in handlers:
    handler = handlers[ext]
else:
    handler = BaseHandler

当然,使用字典的get方法更好!你知道吗

相关问题 更多 >