Hi there,
How do I check if the folder is empty and if it is empty it must create a file?
I got the part to create a new file. I'm just stuck at the part where I need to create this file if the folder directory is completely empty
proc export data=files outfile="C:/List.csv" dbms=tab; run;
List all files in the folder and if 0 number of files is returned, the folder is empty :
How to: List all the files in a folder
https://communities.sas.com/t5/SAS-Programming/How-to-List-all-the-files-in-a-folder/m-p/674065#M202...
Cheers,
Koen
I think you can use the DOPEN and DNUM functions for that, e.g.
filename myfolder "<path to folder>";
data _null_;
dir_id=dopen("myfolder");
if dnum(dir_id)=0 then do;
/* do what is necessary if folder is empty */
end;
rc=dclose(dir_id);
run;
You are mixing data step and macro code, which won't work (macro triggers are resolved before the code is handed off to the data step compiler).
Furthermore, as stated in your other thread, the PROC statement terminates the DATA step anyway.
Next, the DOPEN Function needs a file reference as argument, not a file name.
To make code conditional on the non-existence of files in a directory, you can do
%let path_in= C:/Files;
filename dref "&path_in";
%let did = %sysfunc(dopen(&dref.));
%if %sysfunc(dnum(&dref.)) = 0
%then %do;
/* further code */
%end;
filename d 'c:\temp'; /* specify directory for checking */
data _null_;
did=dopen('d');
if did>0 then do;
filecnt=dnum(did);
call symputx('filecnt',filecnt);
rc=dclose(did);
end;
run;
%if &filecnt=0 %then %do;
/* Describe what to do if the number of files is zero here. */
%end;
Assuming you want to export to the directory, which must be empty, you could just check if the file exists. Depending on the SAS version you are using the following code needs to be wrapped in a macro.
%if not %sysfunc(fileexist(c:/list.csv)) %then %do;
< insert proc export here >
%end;
This macro will export the folder contents to a dataset: https://core.sasjs.io/mp__dirlist_8sas.html
If the dataset is empty, the folder is empty
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.