The FILENAME statement in SAS is a powerful tool used for assigning a fileref (file reference) to an external file or device, enabling seamless data input and output operations within SAS programs.
The FILENAME statement is essential for managing external files in SAS. By creating a fileref, users can reference external files (such as text files, CSVs, or spreadsheets) without specifying the full path each time. This flexibility simplifies file handling and enhances code portability.
The basic syntax for the FILENAME statement is as follows:
FILENAME fileref 'external-file-path';
The FILENAME statement can also include multiple options:
FILENAME myfile '/path/to/your/data.txt';
DATA mydata;
INFILE myfile;
INPUT var1 var2 var3;
RUN;
In this example, the FILENAME statement assigns the fileref myfile
to a text file located at /path/to/your/data.txt
. The DATA step then reads data from this file.
FILENAME tempfile TEMP;
DATA _NULL_;
FILE tempfile;
PUT 'This is a temporary file.';
RUN;
Here, tempfile
is a temporary file that will be deleted at the end of the session. The DATA step writes a line of text to it.
FILENAME myurl URL 'http://example.com/data.csv';
PROC IMPORT DATAFILE=myurl OUT=mydata DBMS=CSV REPLACE;
RUN;
This example demonstrates how to read a CSV file from a URL using the FILENAME statement.
When using the FILENAME statement, users should be mindful of the following:
FILENAME fileref CLEAR;
when they are no longer needed, especially in long-running sessions or applications.The FILENAME statement in SAS is used to assign a logical reference to an external file, streamlining data input and output operations.