pythondictionarymodulelookup

Configuring external user-defined module for multiple scripts in python


I am running several python scripts (one at a time) to manipulate photo, video, and audio files in different combinations in the CWD.

Instead of specifying in each script's body the dozens of "foto_files", for example, what is the best way to call that information from an external user-defined module or lookup or dictionary or whatever file? In this way, I only have to edit 1 file instead of editing all scripts when adding a new extension, etc.

Typical structure:

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


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

Before updating all of my scripts, I am wondering if this is the most appropriate way to configure or there are better solutions and considerations to address?

Module (media_file_types.py):

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

Module import:

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)

Solution

  • I mean, i used .yaml for it. You can specify there types, f.e:

    media_types:
      photo:
        - jpg
        ...
      video:
        ...
    

    And then just make a class where you will retrieve the file types from it:

    class SomeClass:
       def get_ext(self, media_type, with_dot=True):
            ext = self.media_types.get(media_type.lower(), [])
            if with_dot:
                return tuple(f".{ext.lower()}" for ext in ext)
            return tuple(ext.lower() for ext in ext)
    
       def find_files(self, directory='.', media_type=None):
           ext = self.get_ext(media_type)
           return [f for f in os.listdir(directory) if f.lower().endswith(ext)]
    
    config_path = Path(__file__).parent / 'SYS_python' / 'media_config.yaml'
    med = SomeClass(path_to_yaml)
    files = med.find_files(media_type='photo')
    

    Dont forget about __init__ . The same works with all extesting.. Hope this helps