It doesn’t have to be added to a file at all. Create a template sensor helper:
- Settings
- Devices & Services
- Helpers
- Create
- Template > template a sensor (not binary sensor)
Paste your template into the state template box. Note that because you didn’t correctly format your code above, the quotes are wrong, so here’s a fixed version:
{{ states.switch
|selectattr('state','eq','on')|list|length }}
Note that this counts all switches, not just your MQTT ones.