You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多脚本共享媒体文件配置:现有方案是否最优?

统一管理媒体文件扩展名的方案咨询

我需要运行多个Python脚本(同一时间仅运行一个),在当前工作目录(CWD)中处理不同组合的图片、视频和音频文件。为了避免在每个脚本里重复定义大量像foto_files这类的媒体扩展名集合,想通过外部自定义模块、查找表或字典等方式统一调用这些信息,这样新增扩展名时只需修改一个文件,不用改所有脚本。

典型文件结构:

C:\code\script1.py
C:\code\SYS_python\media_file_types.py

运行方式:

(base) P:\aaa\bbb\CWD> python c:\code\script1.py

目前我已经写出了一个模块和导入代码,想在更新所有脚本前确认:这个配置方式是否恰当?有没有更优的解决方案?还有哪些需要考量的事项?

当前模块(media_file_types.py):

foto_file = ('jpg', 'jpeg', 'jfif', 'gif')
video_file = ('mov', 'lrv', 'thm', 'xml')
audio_file = ('3gpp', 'aiff', 'pcm', 'aac')

当前模块导入代码:

import os
import sys

module_path = os.path.join(os.path.dirname(__file__), 'SYS_python')
module_file = os.path.join(module_path, 'media_file_types.py')

if not os.path.exists(module_file):
    print(f"Error: The configuration file '{module_file}' was not found.")
    sys.exit(1)
else:
    sys.path.append(module_path)
    try:
        import media_file_types

        foto_extensions = tuple(f".{ext.lower()}" for ext in media_file_types.foto_file)
        video_extensions = tuple(f".{ext.lower()}" for ext in media_file_types.video_file)
        audio_extensions = tuple(f".{ext.lower()}" for ext in media_file_types.audio_file)
        all_media = foto_extensions + video_extensions + audio_extensions

        foto_files = [f for f in os.listdir('.') if f.lower().endswith(foto_extensions)]
        video_files = [f for f in os.listdir('.') if f.lower().endswith(video_extensions)]
        audio_files = [f for f in os.listdir('.') if f.lower().endswith(audio_extensions)]

        print(f"Found {len(foto_files)} photo files.")
        print(f"Found {len(video_files)} video files.")
        print(f"Found {len(audio_files)} audio files.")

    except ImportError:
        print(f"Error: Could not import the module 'media_file_types' from '{module_path}'.")
        sys.exit(1)
    except AttributeError as e:
        print(f"Error: Missing expected attributes in 'media_file_types': {e}")
        sys.exit(1)

现有方案的合理性

你的方案是恰当且可行的,核心优势很明确:

  • 实现了配置与业务代码分离,新增/修改扩展名只需维护media_file_types.py一个文件,避免重复劳动
  • 基于Python原生模块机制,逻辑简单直接,不需要额外依赖
  • 错误处理完善,能及时捕获模块缺失、属性缺失等问题,避免脚本静默失败

更优解决方案建议

1. 优化模块结构,用字典统一管理

把分散的元组改成字典,扩展性更强,还能方便遍历所有媒体类型,减少业务脚本的重复代码:

# media_file_types.py
MEDIA_EXTENSIONS = {
    'foto': ('jpg', 'jpeg', 'jfif', 'gif'),
    'video': ('mov', 'lrv', 'thm', 'xml'),
    'audio': ('3gpp', 'aiff', 'pcm', 'aac')
}

# 直接在模块里处理好带点的小写扩展名,业务脚本可直接使用
MEDIA_EXTENSIONS_WITH_DOT = {
    key: tuple(f".{ext.lower()}" for ext in value)
    for key, value in MEDIA_EXTENSIONS.items()
}

业务脚本中使用时可以更简洁,还能批量处理所有类型:

import os
import media_file_types

# 直接获取处理好的扩展名
foto_extensions = media_file_types.MEDIA_EXTENSIONS_WITH_DOT['foto']

# 批量收集所有媒体类型的文件
media_files = {}
for media_type, exts in media_file_types.MEDIA_EXTENSIONS_WITH_DOT.items():
    media_files[media_type] = [f for f in os.listdir('.') if f.lower().endswith(exts)]

2. 用纯配置文件替代Python模块

如果需要让非开发人员也能修改扩展名配置,可以用JSON/YAML这类纯配置文件,不需要懂Python语法:

// media_extensions.json
{
    "foto": ["jpg", "jpeg", "jfif", "gif"],
    "video": ["mov", "lrv", "thm", "xml"],
    "audio": ["3gpp", "aiff", "pcm", "aac"]
}

业务脚本读取配置的代码:

import json
import os

config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'SYS_python', 'media_extensions.json')
try:
    with open(config_path, 'r') as f:
        media_config = json.load(f)
    
    foto_extensions = tuple(f".{ext.lower()}" for ext in media_config['foto'])
except FileNotFoundError:
    print(f"Error: 配置文件 {config_path} 不存在")
    sys.exit(1)
except json.JSONDecodeError:
    print(f"Error: 配置文件格式错误")
    sys.exit(1)

这种方式的好处是配置更直观,但需要额外处理文件读取、格式解析的异常。

需要考量的事项

  • 大小写一致性:确保模块/配置里的扩展名和业务脚本的处理逻辑统一(比如都转小写),避免因为文件名大小写导致漏判
  • 路径可靠性:当前用os.path.dirname(__file__)获取脚本目录,若脚本被其他路径的脚本导入,__file__指向可能变化,建议先转绝对路径:
    module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'SYS_python')
    
  • 扩展性:未来如果要新增媒体类型(比如文档),字典结构比分散的元组更容易扩展
  • 版本控制:把配置文件/模块加入版本控制,避免多人修改时出现冲突
  • 默认值兼容:如果某个媒体类型的扩展名集合为空,业务脚本要做好兼容,避免报错
  • 导入路径简化:如果SYS_python目录被加入PYTHONPATH环境变量,可简化导入代码,不用手动修改sys.path

内容的提问来源于stack exchange,提问作者user3026965

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:15:20