Hello Torben,
I suggest to leave doc.save("text.psx") only in it's first occurrence, then use just doc.save().
The reason is related to the fact that doc.save() with the specified path or filename is acting similar to Save As operation from GUI and it re-loads PSX project, but chunk variable is not re-assigned.