Files & Folders
Before reading or writing data you need to find it: build a path that works on every operating system, check whether a file exists, create an output folder, list all the CSV files in a directory. MATLAB has a small set of functions for this, and they behave the same in Octave, with one exception covered below.
Note: the examples on this page run in a fresh, writable folder, so each one first creates the files it needs. The folder's absolute path differs from machine to machine, so the examples never print
pwd.
| Task | Function |
|---|---|
| Current folder | pwd, cd(folder) |
| Build / split a path | fullfile(a, b, ...), fileparts(path), filesep |
| Does it exist? | isfile(name), isfolder(name), exist(name, 'file'), exist(name, 'dir') |
| List contents | dir(pattern), ls |
| Create / remove folders | mkdir(name), rmdir(name), rmdir(name, 's') |
| Copy, move, delete files | copyfile(src, dst), movefile(src, dst), delete(name) |
| Temporary locations | tempdir, tempname |
The current folder
pwd returns the current folder, where MATLAB looks first for files you name without a folder, and where new files are written. cd('data') moves into a subfolder and cd('..') back up. In scripts, changing folders is fragile (if the script stops with an error, you stay in the wrong place), so it is better to leave the current folder alone and build full paths instead.
The current folder is not the same as the search path, the list of folders where MATLAB looks for functions. addpath('tools') adds a folder to it. Data files are not found through the path; open them by their location.
Building paths with fullfile
Windows separates folders with \, Linux and macOS with /. Instead of gluing strings together, use fullfile, which inserts the right separator (filesep) and removes doubled ones. fileparts does the reverse and splits a path into folder, name and extension:
f = fullfile('project', 'results', 'run_01.csv')
[folder, name, ext] = fileparts(f)
[~, name, ext] = fileparts('archive.tar.gz') % only the LAST extension is split off
out = fullfile(folder, [name '_clean' ext]) % a derived file name next to the inputf = project/results/run_01.csv
folder = project/results
name = run_01
ext = .csv
name = archive.tar
ext = .gz
out = project/results/archive.tar_clean.gz
The output shows / because this example ran on Linux; on Windows the same code gives project\results\run_01.csv. Note how fileparts treats archive.tar.gz: the extension is just .gz.
Does it exist?
isfile and isfolder (MATLAB R2017b and later, and Octave) answer the obvious questions with true/false. The older exist returns a code number: 2 for a file, 7 for a folder, 0 if nothing matches (and other codes for variables and functions). Pass the second argument, 'file' or 'dir', so that a variable or function of the same name isn't found instead:
mkdir('data');
fid = fopen(fullfile('data', 'readme.txt'), 'w'); % create a small file
fprintf(fid, 'hello\n');
fclose(fid);
fprintf('isfolder(''data''): %d\n', isfolder('data'));
fprintf('isfile(''data/readme.txt''): %d\n', isfile(fullfile('data', 'readme.txt')));
fprintf('isfile(''data''): %d\n', isfile('data'));
fprintf('exist codes: %d %d %d\n', exist('data', 'dir'), ...
exist(fullfile('data', 'readme.txt'), 'file'), exist('missing.txt', 'file'));isfolder('data'): 1
isfile('data/readme.txt'): 1
isfile('data'): 0
exist codes: 7 2 0
Creating and removing folders
mkdir(name) creates a folder, including any missing parent folders. It returns true on success, and creating a folder that already exists is not an error: it still returns true (with a message in the second output, plus a warning in MATLAB if you don't ask for it). So if ~isfolder(out), mkdir(out); end is a clean, quiet idiom for "make sure the output folder exists".
ok = mkdir(fullfile('output', '2026', 'march')); % creates all three levels
fprintf('created: %d, exists now: %d\n', ok, isfolder(fullfile('output', '2026', 'march')));
[ok, msg] = mkdir('output'); % already there
fprintf('second mkdir: ok = %d, message is empty: %d\n', ok, isempty(msg));
ok = rmdir('output'); % not empty: refuses
fprintf('rmdir on a non-empty folder: %d\n', ok);
ok = rmdir('output', 's'); % 's' removes everything inside too
fprintf('rmdir with ''s'': %d, still there: %d\n', ok, isfolder('output'));created: 1, exists now: 1
second mkdir: ok = 1, message is empty: 0
rmdir on a non-empty folder: 0
rmdir with 's': 1, still there: 0
rmdir(name, 's') deletes the folder and all its contents without asking and without the recycle bin. Use it only on folders your program created.
Listing a folder with dir
dir returns a struct array, one element per entry, with the fields name, folder, date, bytes, isdir and datenum (Octave adds statinfo). A folder listing always includes the entries . (the folder itself) and .. (its parent), so filter them out:
mkdir('inbox');
names = {'notes.txt', 'b.csv', 'a.csv', 'c10.csv', 'c2.csv'};
for k = 1:numel(names)
fid = fopen(fullfile('inbox', names{k}), 'w');
fprintf(fid, '1,2,3\n');
fclose(fid);
end
mkdir(fullfile('inbox', 'archive'));
L = dir('inbox');
L = L(~ismember({L.name}, {'.', '..'})); % drop . and ..
fprintf('%d entries, %d of them folders\n', numel(L), sum([L.isdir]));
csv = dir(fullfile('inbox', '*.csv')); % wildcard: only CSV files
disp(strjoin(sort({csv.name}), ', '))6 entries, 1 of them folders
a.csv, b.csv, c10.csv, c2.csv
Two things to know about the result. The order is not guaranteed to be the same on every system, so sort the names when order matters. And the sorting is alphabetical, so c10.csv comes before c2.csv. Zero-padded names like c02.csv avoid that. The bytes, date and folder fields are useful in your own code (for example, to process only files changed today); they aren't printed here because they differ on every machine.
Searching subfolders
In MATLAB, ** in a dir pattern means "this folder and all subfolders":
% MATLAB: recursive search
L = dir(fullfile('project', '**', '*.txt'));
{L.name}MATLAB output (for the folders created in the next example):
ans =
1×3 cell array
{'top.txt'} {'mid.txt'} {'deep.txt'}Octave 11 treats ** like *: it matches exactly one level of folders, so the same call finds only mid.txt. A short recursive function works in both:
mkdir(fullfile('project', 'sub', 'deeper'));
touch(fullfile('project', 'top.txt'));
touch(fullfile('project', 'sub', 'mid.txt'));
touch(fullfile('project', 'sub', 'deeper', 'deep.txt'));
touch(fullfile('project', 'sub', 'image.png'));
files = find_files('project', '.txt');
for k = 1:numel(files)
disp(files{k})
end
function files = find_files(folder, ext)
% All files below FOLDER whose extension is EXT, as relative paths.
files = {};
L = dir(folder);
for k = 1:numel(L)
name = L(k).name;
if any(strcmp(name, {'.', '..'}))
continue
end
p = fullfile(folder, name);
if L(k).isdir
files = [files, find_files(p, ext)]; % recurse into subfolders
else
[~, ~, e] = fileparts(name);
if strcmpi(e, ext)
files{end+1} = p;
end
end
end
files = sort(files);
end
function touch(name)
% Create an empty file.
fid = fopen(name, 'w');
fclose(fid);
endproject/sub/deeper/deep.txt
project/sub/mid.txt
project/top.txt
See Recursion for more on functions that call themselves.
Copying, moving and deleting
copyfile(src, dst) and movefile(src, dst) take a file (or folder) and a destination, which can be a new name or an existing folder; both return true on success. delete(name) removes files and accepts wildcards like delete('*.tmp'). Deleted files do not go to the recycle bin unless you turn that on with recycle('on').
mkdir('work');
fid = fopen(fullfile('work', 'draft.txt'), 'w');
fprintf(fid, 'version 1\n');
fclose(fid);
copyfile(fullfile('work', 'draft.txt'), fullfile('work', 'backup.txt'));
movefile(fullfile('work', 'draft.txt'), fullfile('work', 'final.txt')); % = rename
L = dir(fullfile('work', '*.txt'));
disp(strjoin(sort({L.name}), ', '))
delete(fullfile('work', 'backup.txt'));
fprintf('backup still there: %d\n', isfile(fullfile('work', 'backup.txt')));
ok = copyfile('no_such_file.txt', 'copy.txt');
fprintf('copying a missing file: ok = %d\n', ok);backup.txt, final.txt
backup still there: 0
copying a missing file: ok = 0
Asking for the status output (ok = copyfile(...)) turns failures into a false return value instead of an error, so the script can react. Without an output, a failed copyfile stops the script with an error.
Temporary files
tempdir returns the system's folder for temporary files, and tempname a unique, unused path inside it. Use them for intermediate results you don't want to keep, and delete them when done:
tmp = [tempname, '.csv']; % e.g. /tmp/oct-Xa12bc.csv or C:\Users\...\Temp\tp3f2a.csv
dlmwrite(tmp, magic(3));
M = dlmread(tmp);
delete(tmp);Summary
- Build paths with
fullfileand split them withfileparts; never hard-code/or\. isfile/isfolder(orexist(name, 'file'/'dir')) check before you read;mkdircreates nested folders and is harmless if they already exist.dirreturns a struct array: drop.and.., use wildcards for patterns, and sort the names yourself.**is recursive in MATLAB but not in Octave 11; a small recursive function works everywhere.rmdir(name, 's')anddeleteare permanent.
Next: Reading & Writing Text Files. Learn more: Python's version of these tasks is in Python File Handling.
Test yourself
What does [p, n, e] = fileparts(fullfile('data', 'jan.csv')) return in n?
'data''jan''jan.csv''.csv'
Which entries does dir('inbox') always include besides the files?
- None
.and..- Only hidden files
- The parent folder's files
What does exist('results', 'dir') return if results is a folder?
- 1
- 2
- 7
- true