What you try to do isn't possible this way with ssh. You have to understand how ssh works. It's abbreviation means secure shell and it opens a console (shell) on the connected pi2. It is a software terminal and keyboard doing just the same as a monitor and keyboard direct connected to pi2. With this you can't simply store content to a file on pi1 because there is no connection to it.
With ssh you are working on pi2 and not on pi1. The latter only give you the screen and the keyboard. You can run your script on pi2 within the ssh console and write to a file on rpi2. Then you have to copy it from pi2 to pi1 by network. There is a simple program scp (just made from ssh) that can do it. To copy the file from pi2 to pi1 from within the ssh console you can execute:
pi2 ~$ scp /path/to/file-on-pi2.txt pi@pi1:/path/to/file-on-pi1-now.txt
Or copy the same file staying on pi1:
pi1 ~$ scp pi@pi2:/path/to/file-on-pi2.txt /path/to/file-on-pi1-now.txt
There are other ways to have direct access to files on a remote device with network shares using samba or with exports using NFS.