How to read text file and add to input select

There is a MUCH easier way to do this if you just need a list of the file names and the files reside in a folder on your Home Assistant server. The problem I had with the solution @123 suggested is that I need to match a URL with a name in a CVS file.

In this case, to just get a list of file names you can use the folder sensor. The folder contents are listed in the attributes (you can set filters on the sensor if necessary).

Then use an automation to populate the input select with the file names. Note the folder path must be listed in allowlist_external_dirs if it doesn’t reside in /www (which is included automatically)

The input select will populate on a restart and then anytime the folder contents change (eg adding a file). Note it takes a moment or two for the file sensor to update.

sensor:
  - platform: folder
    folder: '/config/www/alarm_clock_sounds'
    filter: '*'

input_select:
  mp3_files:
    name: "MP3 Files"
    options:
      - None Available

automation:
  - id: load_mp3_select
    alias: "Load MP3 Select"
    description: "Load/Update MP3 select list."
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.alarm_clock_sounds
    action:
      - service: input_select.set_options
        target:
          entity_id: input_select.mp3_files
        data:
          options: >
            {% set files = namespace(value=[]) %}
            {% for item in state_attr('sensor.alarm_clock_sounds','file_list') %}
            {% set files.value = files.value + [item] %}
            {% endfor %}
            {{ files.value }}

image

2 Likes