Write data to csv file

  • 21 June 2020
  • 2 replies


I'm looking for a way to write to a .csv file. 

I found the keywords for OPEN and READ to work with a data file, but did not find how WRITE to a csv file. 

Can someone help please?

Raphael Levy

2 replies


Raphael -  

There might be better ways, but I've been using this method for many years.  See code below. Some key items:

Use OUTPUT to redirect print statements.

The file is CSV only because the print statments include a ' , ' as a seperator.

I use the append mode because the first thing to go into the file is the lens name, then each print statement is appended.

I convert the file from unicode to ANSI. Matlab and other programs handle ANSI text files better, or least that was true.

Best regards,





! File: Eval_T_distance


  direc_log$ = 'C:\Dropbox\'

  log_filename$ = direc_log$ + 'data.csv'

  output log_filename$

    current_lens_name$ =  $FILENAME()    

  print current_lens_name$

  output screen    


  focus_adjust_surface = 3


for t_tele=90,115,2.5

       Setsurfaceproperty focus_adjust_surface,thic, t_tele


      ! this next line updates the merit function...

      ! The merit function is in the lens, but you could load it...

     cause_evaluation = MFCN()

     ! pull out the value from the merit function....



    ! You have to print to the screen AND to a filename to see what is going on...

   format 7.4

   print t_tele, ' ,  ',rms_diam_mm


   !format 10.7

   output log_filename$, append

   print t_tele, ' ,  ',rms_diam_mm

   output screen



CONVERTFILEFORMAT log_filename$, unicode_to_ansi

!showfile log_filename$, 1

label lbl_end

print ' '

print ' --- ! ALL DONE ---'

print ' --- ! Close this window before opening a new lens!!! ---'


Userlevel 7
Badge +3

Hi, try this:

! Write out a comma separated list of 5 variables A, B, C, D and E
! Define the delimiter
delimiter$ =', '
A = 1
B = 2
C = 3
D = 4
E = 5
! Now write out a comma-separated list
PRINT A, delimiter$, # the comma at the ends means no CR/LF
PRINT B, delimiter$,
PRINT C, delimiter$,
PRINT D, delimiter$,
PRINT E # no delimiter, and no comma at end so also write a CR/LF
Print 'Program End'


Note that the delimiter contains a comma and a space. The space is not required for CSV, but it makes the output more human-friendly:

Executing C:\Users\markg\Documents\Zemax\MACROS\CSV.ZPL.

1.0000, 2.0000, 3.0000, 4.0000, 5.0000

Program End

Then as John shows, redirect the PRINT statements to a file using OUTPUT. Use a filename ending in .CSV. Also use FORMAT to give the decimal precision you need.

John, does Matlab still not accept Unicode text? Sheesh, it's only been the Windows standard text format since Windows 95...

- Mark