You're on the right track. What would work better is using [find] instead of targeting the item number. Then you are only looping through the entries that match your query. The following code loops through all firewall filter rules that contain # in the comment. The delay is there because for some reason after creating a new file, it is not immediately accessible for writing.
/ip firewall filter
:foreach i in=[find comment~"#"] do={
:local filename ([get $i comment] . " - " . [get $i src-address])
:local status [get $i disabled]
:if ($status = true) do={:set status "disabled"} else={:set status "enabled"}
/file print file="$filename"
:delay 1s
/file set [find name~"$filename"] contents=$status
}
And... this is just a bonus for verifying the script worked. It finds the files that contain # in the name and displays their contents. Copy/paste into the terminal.
/file
:foreach i in=[find name~"#"] do={
:put ([get $i name] . " - " .[get $i contents])
}