ZetCode

CSV and text data in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

Comma-separated values are the simplest way to exchange tabular data: every line is a record, and commas separate the fields. Pascal has no CSV type in the language, but the run-time library provides TStringList, which can split a line into fields, quote fields that contain separators, and load or save a whole file. This article reads a table into records, handles quoted fields, computes statistics, and writes a formatted report.

A first CSV file

TStringList is a list of strings with file support. Setting Delimiter to a comma and assigning a line to DelimitedText splits the line into the list's items. The same property, read in the other direction, joins the items back into a line. The program below writes three rows to a file, loads them again, and prints one field per column.

readfields.pas
program readfields;
{$mode objfpc}{$H+}

uses
  Classes, SysUtils;

var
  Data: TStringList;
  Row: TStringList;
  I: Integer;

begin
  Data := TStringList.Create;
  Row := TStringList.Create;
  try
    Data.Add('name,age,city');
    Data.Add('Alice,30,Bratislava');
    Data.Add('Bob,25,Kosice');
    Data.Add('Carol,41,Zilina');
    Data.SaveToFile('people.csv');

    Data.LoadFromFile('people.csv');
    WriteLn('lines: ', Data.Count);
    for I := 1 to Data.Count - 1 do
    begin
      Row.Delimiter := ',';
      Row.DelimitedText := Data[I];
      WriteLn(Row[0], ' | ', Row[1], ' | ', Row[2]);
    end;
  finally
    Row.Free;
    Data.Free;
  end;
end.

The header is a normal line and is skipped by starting the loop at index 1. SaveToFile writes the list with the platform line ending, and LoadFromFile reads it back. The inner list is reused for every row; assigning DelimitedText replaces its previous contents. Both lists are freed in a finally block, so a file error does not leak them.

$ fpc -gl readfields.pas
$ ./readfields
lines: 4
Alice | 30 | Bratislava
Bob | 25 | Kosice
Carol | 41 | Zilina

Quoted fields

A field that contains a comma, a quote, or a line break cannot be written plainly, because the separator would split it. CSV wraps such a field in double quotes and doubles any quote inside it. TStringList follows that convention when StrictDelimiter is False: it treats quotes as field delimiters and returns the unquoted text.

quoted.pas
program quoted;
{$mode objfpc}{$H+}

uses
  Classes, SysUtils;

var
  Row: TStringList;
  I: Integer;

begin
  Row := TStringList.Create;
  try
    Row.Delimiter := ',';
    Row.StrictDelimiter := False;
    Row.DelimitedText := '"Smith, John",42,"New York, NY"';
    WriteLn('fields: ', Row.Count);
    for I := 0 to Row.Count - 1 do
      WriteLn(I, ': [', Row[I], ']');
  finally
    Row.Free;
  end;
end.

The line yields three fields, not five: the comma inside the first quoted field and the one inside the third belong to the data. With StrictDelimiter set to True, the quotes lose their special meaning and the same line is split at every comma. Writing quoted output works the same way: add the unquoted values to a list and read its DelimitedText property.

$ fpc -gl quoted.pas
$ ./quoted
fields: 3
0: [Smith, John]
1: [42]
2: [New York, NY]

Reading a table into records

For real work the text fields must become typed values. The next program declares a TPerson record and a dynamic array of records, converts the age with StrToInt, and computes the average age. The number of records is known from the line count, so the array is sized once with SetLength.

csvstats.pas
program csvstats;
{$mode objfpc}{$H+}

uses
  Classes, SysUtils;

type
  TPerson = record
    Name: string;
    Age: Integer;
    City: string;
  end;

var
  Data: TStringList;
  Row: TStringList;
  People: array of TPerson;
  I, Total: Integer;

begin
  Data := TStringList.Create;
  Row := TStringList.Create;
  try
    Data.Add('name,age,city');
    Data.Add('Alice,30,Bratislava');
    Data.Add('Bob,25,Kosice');
    Data.Add('Carol,41,Zilina');
    Data.Add('David,35,Presov');

    SetLength(People, Data.Count - 1);
    Total := 0;
    for I := 1 to Data.Count - 1 do
    begin
      Row.Delimiter := ',';
      Row.DelimitedText := Data[I];
      People[I - 1].Name := Row[0];
      People[I - 1].Age := StrToInt(Row[1]);
      People[I - 1].City := Row[2];
      Total := Total + People[I - 1].Age;
    end;

    WriteLn('people: ', Length(People));
    for I := 0 to High(People) do
      WriteLn(Format('%-6s %3d  %s', [People[I].Name, People[I].Age,
        People[I].City]));
    WriteLn('average age: ', Total / Length(People):0:2);
  finally
    Row.Free;
    Data.Free;
  end;
end.

The program name is csvstats, not people, because Pascal is case-insensitive and the program name shares the namespace with its variables: a program called people with a variable People is rejected with Duplicate identifier "people". The format string %-6s %3d left-aligns the name and right-aligns the age, and Total / Length(People):0:2 prints the average with two decimals.

$ fpc -gl csvstats.pas
$ ./csvstats
people: 4
Alice   30  Bratislava
Bob     25  Kosice
Carol   41  Zilina
David   35  Presov
average age: 32.75

Writing a report

A report is ordinary text with aligned columns. Format pads each value to a fixed width, and a TStringList collects the lines before they are saved. The example also shows the other direction of DelimitedText: adding values that contain commas produces quoted CSV automatically.

report.pas
program report;
{$mode objfpc}{$H+}

uses
  Classes, SysUtils;

var
  Row, Out: TStringList;
  I: Integer;

begin
  Row := TStringList.Create;
  Out := TStringList.Create;
  try
    Row.Delimiter := ',';
    Row.Add('Smith, John');
    Row.Add('42');
    Row.Add('New York, NY');
    Out.Add(Row.DelimitedText);
    Out.Add('Alice,30,Bratislava');
    Out.SaveToFile('contacts.csv');
    WriteLn('--- contacts.csv ---');
    for I := 0 to Out.Count - 1 do
      WriteLn(Out[I]);

    Out.Clear;
    Out.Add('name          age');
    Out.Add('------------- ---');
    Out.Add(Format('%-13s %3d', ['Alice', 30]));
    Out.Add(Format('%-13s %3d', ['Bob', 25]));
    Out.SaveToFile('report.txt');

    WriteLn('--- report.txt ---');
    Out.LoadFromFile('report.txt');
    for I := 0 to Out.Count - 1 do
      WriteLn(Out[I]);
  finally
    Out.Free;
    Row.Free;
  end;
end.

The first list is joined into one CSV line, with the name and the city quoted because they contain a comma. The second part clears the list and writes a plain text table. The saved report is loaded back and printed, which proves that the line ending and the padding survived the round trip.

$ fpc -gl report.pas
$ ./report
--- contacts.csv ---
"Smith, John",42,"New York, NY"
Alice,30,Bratislava
--- report.txt ---
name          age
------------- ---
Alice          30
Bob            25

Encodings, line endings, and errors

TStringList reads and writes bytes; it does not convert between encodings. A file saved as UTF-8 stays UTF-8, and Length counts bytes rather than characters, so a name with accented letters occupies more bytes than it has letters. For a robust reader, open the file in a try..except block and report EInOutError when it is missing, and validate every numeric field with TryStrToInt instead of letting StrToInt raise EConvertError. Fields can also be split by hand with Pos and Copy when the file uses a separator that is not a comma.

For files larger than memory, read them line by line with a TextFile and ReadLn instead of loading the whole list. The same record and dynamic-array approach then works with a growing array or a TList<TPerson>. The strings article covers the string routines used here, and the formatted output article explains the width and precision fields in detail.

Source

Free Pascal: TStringList

Free Pascal: TStrings.DelimitedText

Comma-separated values on Wikipedia

In this article we wrote and read CSV files with TStringList, handled quoted fields, loaded a table into an array of records, computed statistics, and produced a formatted report. The series continues with threads and synchronization in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.