How to invoke a script when closing any file with a given extension
If the script could also be run when you open a file (or in other cases), you could use opensnoop.

~/test:

#!/bin/bash

while :; do
    opensnoop | grep -Ev ' (mdworker|mds|filecoordinatio|revisiond|Finder|Alfred) ' | grep -m1 '/Users/username/Folder/.*\.txt'
    say a
    sleep 1
done


/Library/LaunchAgents/test.plist:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;Label&lt;/key&gt;
    &lt;string&gt;test&lt;/string&gt;
    &lt;key&gt;Program&lt;/key&gt;
    &lt;string&gt;/Users/username/test&lt;/string&gt;
    &lt;key&gt;RunAtLoad&lt;/key&gt;
    &lt;true/&gt;
&lt;/dict&gt;
&lt;/plist&gt;


chmod +x ~/test, sudo chown root /Library/LaunchAgents/test.plist, and launchctl load /Library/LaunchAgents/test.plist.