Modify how a script prints the output?
Let's simplify...
cmd.distance(xx,xxx) accepts two selector strings and is fine with and state 1. And best of all if you select multiple atoms it gives you the smallest distance!
So all you need to do is:
# measure
d_O = cmd.distance('UNL and element O', 'resi 312 and name ND2')
d_N = cmd.distance('UNL and element N', 'resi 113 and name OD2')
# write  
f=open(&quot;dst4.txt&quot;, 'w')
f.write(f'Lig_N D113 {d_N:.2f}\n')
f.write(f'Lig_O N312 {d_O:.2f}\n')
f.close()

If you are using python 2 (if so do note pymol scripting is better in 3), then the second bit is
f=open(&quot;dst4.txt&quot;, 'w')
f.write('Lig_N D113 %.2f\n' % (d_N,))
f.write(f'Lig_O N312 %.2f\n' % (d_O,))
f.close()

Unsolicited coding tips
A few unsolicited tips... Your original script is rather over-complicated and obfuscated and uncommented, so for better legibility why not do:

cmd.iterate_state is always harder to follow than the for atom in get_model('xxxx').atoms synthax
unless you are stuck with python 2, use f-strings not the %s sprintf style formatting
the /x/x/x/x selector synthax is never as readable as the longer
resi/resn/name selection algebra.

Code golf is always tempting, but it can result in future-you getting stuck as happened here...