writelines

Writes text lines to a file, one string per line.

Category: Data Import and Analysis > Data Import and Export

Syntax

writelines(str, filename)

Writes each element of the string array str as a line of filename.

writelines(str, filename, 'WriteMode', 'append')

Adds the lines at the end of an existing file instead of replacing it.

Description

writelines is the plain-text counterpart of readlines. Each element of str ends with a line break, and the text is stored as given, so nothing is quoted or converted. It is the simplest way to save logs, notes or generated code.

Escape sequences inside a quoted literal are not interpreted: 'a\tb' is written with a backslash and a t. Build the text with sprintf when you need real tabs or other control characters.

Input arguments

str
String array, character vector or cell array of text.
filename
Output file name.
'WriteMode'
'overwrite' (default) or 'append'.

Example

Write, then append

writelines(["first"; "second"], 'lines_demo.txt');
writelines("third", 'lines_demo.txt', 'WriteMode', 'append');
type lines_demo.txt
Output

first
second
third

See also

readlines fileread fprintf type