Search code examples
csvsasexport-to-csv

SAS CSV export has an unwanted leading comma in each row


I'm new to SAS and am struggling to export data to CSV. My code successfully exports a file but it has a leading comma on each non-header row that creates a misalignment.

I feel like I am missing something obvious and could really use some help. Thank you!

data _null_;
file "/export.csv";
set "/table" (keep= field1 field2 'field 3'n);
if _n_ = 1 then 
    do;       /* write header row */
        put "field1" 
            ',' 
            "field2"
            ','
            "field3";
    end;
    do;
        put (_all_) (','); 
    end;
run;

My output ends up looking like this...

field1,field2,field3,

,x ,y ,z

,a ,b ,c

,d ,e ,f...

or

Field1 Field2 Field3
x y z
a b c
d e f

Solution

  • Since you seem to already know the variable names (since you have hard coded the header line) then just modify the PUT statement to not insert the extra comma.

    put field1 (field2 'field 3'n) (',');
    

    But really you should just tell SAS you are writing a delimited file by using the DSD option.

    /* write header row */
    data _null_;
      file "/export.csv";
      put "field1,field2,field 3";
    run;
    
    
    /* Add the actual data */
    data _null_;
      file "/export.csv" dsd mod ;
      set table;
      put field1 field2 'field 3'n ;
    run;
    

    If you don't actually know the variable names in advance then just ask SAS to generate them for you.

    /* write header row */
    proc transpose data=table(obs=0) out=names;
      var _all_;
    run;
    data _null_;
      file "/export.csv" dsd;
      set names;
      put _name_ @;
    run;
    
    /* Add the actual data */
    data _null_;
      file "/export.csv" dsd mod ;
      set table ;
      put (_all_) (+0);
    run;