How to write a cube file?
I would recommend using the functional PySCF cubegen script as a starting point for your own script. (https://sunqm.github.io/pyscf/_modules/pyscf/tools/cubegen.html)

If we have a grid defined with nx ny and nz points along the three axes, generating the cube file is just a nested loop over z, y, and x. (In that order) You should end up with nz lines of output each with nx*ny entries.