Cutting Fields From A CSV File
December 7, 2021
Over at Stack Overflow, I answered a question about cutting fields from a CSV file. Paraphrasing:
A file in CSV format has a header row containing field names followed by record rows containing actual data. The user wants to cut fields from the CSV file to create a new CSV file containing only the specified fields, specifying the fields by name instead of using their ordinal position.
Your task is to write a program to cut fields from a CSV file by name. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Using Pascal:
program CSVSplitter;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, Classes;
procedure Split(inputFileName, fieldName, outputFileName: String);
var
inputFile, outputFile: TextFile;
header, line: String;
columnList: TStringList;
index: Integer;
begin
AssignFile(inputFile, inputFileName);
columnList := TStringList.Create;
try
Reset(inputFile);
if Not Eof(inputFile) then
Readln(inputFile, header);
except
on E: Exception do
begin
writeln('Exception occurs during reading file ' + inputFileName + ' -> ' + E.Message);
end;
end;
columnList.Free;
CloseFile(inputFile);
CloseFile(outputFile);
end;
begin
if ParamCount = 3 then
begin
if FileExists(ParamStr(1)) then
begin
Split(ParamStr(1), ParamStr(2), ParamStr(3));
end
else
writeln('File ' + ParamStr(1) + ' cannot be found.');
end
else
writeln('Usage: ' + ExtractFileName(ParamStr(0)) + ' ');
end.
I found the use of the word “cut” and “field” instead of, say, “select” and “column”, confusing.
Using Smalltalk, with my own CSV library, I’ve lightly tested this:
Hello!
I’ve been a lurker of your blog for a few years now I was wondering why you suddenly stopped I hope we hear from you again.