Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 45 ยท Data and Files

Reading and Writing Files

Read and write text, CSV and MAT files in MATLAB and Octave with fopen, fgetl, fprintf, fclose, load, save, readmatrix and importdata, with in-memory Python stand-ins.

Real programs read measurements from disk and write results back. MATLAB and Octave give you two levels of tools. The low-level ones (fopen, fgetl, fprintf, fclose) work line by line and handle any text format. The high-level ones (load, save, readmatrix, importdata) move whole matrices in one call.

Files cannot be touched from a browser page, and MATLAB and Octave are not installed on this site, so the MATLAB code below is read-only. The runnable TryIts are Python stand-ins that work on files held in memory (io.StringIO and io.BytesIO), which behave like open files without writing anything to your disk. The ideas carry over directly.

Two ways to handle files

Low level fopen, fgetl, fprintf, fclose.
High level load, save, readmatrix, importdata.
1 / 3

The current folder

Relative file names are looked up in the current folder (see The Desktop, Command Window and Scripts). pwd prints it, cd changes it, ls lists files and exist('data.csv', 'file') returns 2 when the file is found. Check before reading, or pass full paths built with fullfile('data', 'run1.csv'), which uses the right separator on each operating system.

Writing text with fprintf

You met fprintf for screen output in Variables, Output and Help. With a file identifier as the first argument, the same call writes into a file instead.

MATLAB
fid = fopen('scores.txt', 'w');          % 'w' = write, replaces the file
if fid == -1
    error('Could not open scores.txt');
end
fprintf(fid, 'name,score\n');
fprintf(fid, '%s,%d\n', 'Ada', 91);
fprintf(fid, '%s,%d\n', 'Grace', 84);
fclose(fid);

fopen returns a non-negative integer handle, or -1 if it failed (missing folder, no permission). The common modes are 'r' read (the default), 'w' write and replace, 'a' append, and 'r+' read and write. Always call fclose, otherwise the last lines may stay unflushed in a buffer. Text mode is the default; add 'b' for binary files.

fprintf reuses its format for every remaining element, column by column. That makes it easy to write a whole matrix, but mind the orientation:

MATLAB
A = [1 2 3; 4 5 6];
fprintf(fid, '%d %d %d\n', A');          % transpose so rows come out as rows

Without the ', the numbers would be written in column-major order (1, 4, 2, 5, 3, 6).

Python Write lines to an in-memory file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading text line by line

fgetl returns the next line without its newline, and -1 (a number, not text) at the end of the file; fgets keeps the newline. A while loop with ischar is the standard pattern:

MATLAB
fid = fopen('scores.txt', 'r');
header = fgetl(fid);                     % 'name,score'
total = 0; n = 0;
line = fgetl(fid);
while ischar(line)
    parts = strsplit(line, ',');         % {'Ada', '91'}
    total = total + str2double(parts{2});
    n = n + 1;
    line = fgetl(fid);
end
fclose(fid);
fprintf('Mean score: %.1f\n', total / n);   % Mean score: 87.5

Other readers: fscanf(fid, '%f', [3 Inf]) reads numbers into a matrix, textscan reads delimited columns of different types into a cell array, and fileread('scores.txt') returns the whole file as one character vector (see Strings and Character Arrays for what to do with it).

Python Read it back line by line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Numeric files: readmatrix, csvread and friends

When a file is a plain grid of numbers, one call is enough.

MATLAB
M = readmatrix('measurements.csv');      % MATLAB R2019a and later
M = csvread('measurements.csv');         % older, still works in Octave
M = dlmread('data.txt', ';');            % any delimiter, here ';'
writematrix(M, 'copy.csv');              % MATLAB R2019a and later
csvwrite('copy.csv', M);                 % older name

readmatrix skips a text header line on its own and turns empty cells into NaN. csvread cannot cope with a header, so use csvread('f.csv', 1, 0) to skip one row and zero columns. Octave has csvread/dlmread everywhere; readmatrix appeared in recent Octave versions, so scripts meant for both should use dlmread or csvread.

For mixed columns (text and numbers), readtable returns a table in MATLAB (see Tables and Maps), and importdata guesses the format and returns a struct with fields data, textdata and colheaders:

MATLAB
S = importdata('scores.csv');
S.colheaders      % {'name', 'score'}  (when the headers can be detected)
S.data            % numeric part only
Python Numbers in, numbers out (readmatrix stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

MAT files: load and save

A MAT file stores variables exactly as they are, with their names, types and sizes, with no rounding. Use it for results you will reload in MATLAB or Octave.

MATLAB
A = magic(4);
label = 'run 7';
save('results.mat', 'A', 'label');       % save chosen variables
save('everything.mat');                  % save the whole workspace
clear A label
load('results.mat');                     % recreates A and label
S = load('results.mat');                 % or keep them in a struct: S.A, S.label
whos -file results.mat                   % list contents without loading

Prefer the struct form S = load(...): it cannot overwrite variables you already have. MATLAB's default format is version 7 (compressed); add '-v7.3' for variables over 2 GB (HDF5-based). Octave saves in its own text format by default, so use save('-mat', 'results.mat', 'A') (or -v7) when the file must open in MATLAB. Python can read the classic formats with scipy.io.loadmat.

save('data.txt', 'A', '-ascii') writes plain numbers, but without names and at limited precision, so it is a poor archive format.

Python Save and load variables (MAT stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Good habits

  • Check the result of fopen and report the file name in the error message.
  • Close files, even after an error: put fclose after the loop, and in larger code use onCleanup(@() fclose(fid)).
  • Use fullfile instead of gluing paths with / or \.
  • Do not hard-code absolute paths like C:\Users\me\data.csv; keep data next to the script or pass the folder in as an argument.
  • Never overwrite raw data. Read from raw/, write to results/.
  • Choose text/CSV to share with other programs and MAT to reload exactly in MATLAB or Octave.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does fopen return when it cannot open a file?

    A valid file identifier is non-negative; -1 signals failure, so check it before reading or writing.
  2. 2. What does fgetl return at the end of the file?

    fgetl returns the numeric value -1 at the end, which is why loops test ischar(line).
  3. 3. You call fprintf(fid, '%d %d ', A) for a 2-by-2 matrix A. In which order are the numbers written?

    Matrices are stored column-major, so fprintf consumes the elements column by column. Pass A' to write rows as rows.
  4. 4. Why is S = load('results.mat') often safer than load('results.mat')?

    The struct form keeps the loaded variables as fields (S.A) instead of dropping them into the workspace, where they could replace existing ones.

Summary

  • fopen, fgetl/fscanf, fprintf, fclose handle any text file line by line; check for -1 and always close.
  • fprintf writes matrices column by column, so transpose to write rows.
  • readmatrix/csvread/dlmread read numeric grids; importdata and readtable handle headers and mixed columns.
  • save and load store variables exactly in MAT files; prefer S = load(...).
  • Octave needs -mat or -v7 to write files that MATLAB opens.
  • The Python TryIts use in-memory files, so nothing touches your disk.

Next, deal with what real data looks like in Cleaning and Preparing Data.