Looks like the original file is opened and read line by line into a temporary file, inserting the line that needs to be added. After all lines are read from the original file to the temp file, both files are closed and the temp file is renamed to the original filename. So the original file isn't having its permissions changed, it's being overwritten by a new file with the default permissions. Add a line at the bottom of the script after the rename:
chmod 0755, 'writeline.cgi';